Redirect all http AND https non-www URLS to https:

2019-01-11 11:42发布

问题:

For reasons much too long and complex to get into (it involves several layers of corporate red tape resulting in someone else not purchasing a wildcard SSL certificate I requested), I have to set up a domain to redirect all requests to https://www.xyz.com – secure protocol with the www subdomain.

So: http://xyz.com, http://www.xyz.com, and https://xyz.com should ALL redirect to https://www.xyz.com.

My .htaccess-fu is weak at best and I can't seem to get this to work. Note: hosting is on Media Temple if that makes a difference.

So far, my .htaccess file looks like so:

RewriteEngine On
RewriteCond %{HTTPS} !^on$
RewriteRule (.*) https://www.xyz.com/$1 [R,L]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Both http://xyz.com and http://www.xyz.com are redirecting to https://www.xyz.com, so yay. However, https://xyz.com is not redirecting to https://www.xyz.com and is thus throwing a security warning page:

This is probably not the site you are looking for!
You attempted to reach xyz.com, but instead you actually reached a server identifying itself as www.xyz.com. This may be caused by a misconfiguration on the server or by something more serious. An attacker on your network could be trying to get you to visit a fake (and potentially harmful) version of xyz.com.
You should not proceed, especially if you have never seen this warning before for this site.

Any help in getting me past this one final hump would be muchly appreciated!

回答1:

This is very much possible. use the following code. this works for me.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1


回答2:

In case anyone from the future (HELLO PEOPLE OF THE FUTURE) stumble across this, I asked the same question and had it answered over at Server Fault.

Short version: impossible.

Long version: https://serverfault.com/questions/523199/redirect-all-http-and-https-non-www-urls-to-https-www-example-com-via-htaccess



回答3:

Even though this issue is very old.

If found it googeling the exact same issue. After the Code provided here didn't help. I tried and tried.

This one worked for me:

     RewriteCond %{HTTPS} off
     RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
     RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
     RewriteCond %{HTTPS} off
     RewriteCond %{HTTP_HOST} !^www\. [NC]
     RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
     RewriteCond %{HTTPS} on
     RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
     RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]

Fixed the issue for me without any Loops or other errors. Maybe it will help someone else.