Reputation: 43
The goal is to permanently redirect BOTH HTTP and www to https://example.com
on a shared hosting service with an active SSL.
Several attempts; some involving a rule like:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
and other attempts involving, for example, rules like the StackOverflow post by Rahil Wazir involving:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} !^443
RewriteRule ^(.*)$ http://example.com/$1 [L, R=301]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} ^443
RewriteRule ^(.*)$ https://example.com/$1 [L, R=301]
Thus far, no attempt has completely met the goal. Can you help?
Note that https://www.example.com
should also permanently redirect to https://example.com
.
Upvotes: 2
Views: 159
Reputation: 45914
Providing you are not implementing HSTS (in which case you should implement two separate redirects, the first being HTTP to HTTPS on the same host) then you can do something like the following at the top of your .htaccess
file:
RewriteEngine On
# Redirect HTTP to HTTPS (and www to non-www)
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule (.*) https://example.com/$1 [R=302,L]
The HTTPS
server variable is an alternative (and arguably more readable) way of checking to see whether HTTPS is enabled or not, instead of explicitly checking the SERVER_PORT
.
Note this is a 302 (temporary) redirect. Only change it to a 301 (permanent) redirect when you have tested that it is working OK.
You will need to clear your browser cache before testing.
Problems with the directives you posted:
RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L]
This only redirects HTTP to HTTPS. It won't canonicalise a request for https://www.example.com/
. This is also a temporary (302) redirect.
RewriteCond %{HTTP_HOST} ^www.example.com$ RewriteCond %{SERVER_PORT} !^443 RewriteRule ^(.*)$ http://example.com/$1 [L, R=301]
Apart from being syntactically invalid (you have a space inbetween the RewriteRule
flags - which will result in a 500 Internal Server Error), this only redirects www
and HTTP. But it redirects to HTTP, not HTTPS! Consequently, it won't canonicalise/redirect http://example.com/
or https://www.example.com
.
RewriteCond %{HTTP_HOST} ^www.example.com$ RewriteCond %{SERVER_PORT} ^443 RewriteRule ^(.*)$ https://example.com/$1 [L, R=301]
Again, the RewriteRule
directive is syntactically invalid for the reason mentioned above. This only redirects www
and HTTPS. Consequently, it won't canonicalise http://example.com/
or http://www.example.com
.
Upvotes: 1