Reputation: 29301
I have the following rules in my .htaccess:
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
This causes domains such as http://www.domain.com
to be redirected to https://domain.com
as well as http://www.sub.domain.com
to be redirected to https://sub.domain.com
.
I would like to expand this rule to include redirection from http://domain.com
to https://domain.com
and http://sub.domain.com
to https://sub.domain.com
.
I've found a couple of examples online, but they don't seem to do quite what I would like:
How to redirect http to https and https://www to https:// This example appears to hardcode domain and not support subdomain?
Redirect all http AND https non-www URLS to https://www.xyz.com via htaccess This is close, but is going to www not away from it which changes the regex.
I know this isn't a difficult change, but PHP/.htaccess files aren't my strongest suite. Could someone enlighten me?
Upvotes: 1
Views: 317
Reputation: 785176
Here is a rule that lets you do both redirects in one single rule:
RewriteCond %{HTTP_HOST}::%{HTTPS} ^(?:www\.(.+?)::o(?:ff|n)|(?!www\.)(.+?)::off)$ [NC]
RewriteRule ^ https://%1%2%{REQUEST_URI} [R=302,L,NE]
It will do following redirections:
http://domain.com => https://domain.com
http://www.domain.com => https://domain.com
https://www.domain.com => https://domain.com
http://www.sub.domain.com => https://sub.domain.com
Upvotes: 2