force all domains https with www

2019-03-28 09:28发布

问题:

I tried 12 different solutions on this forum and non of them will work. I want all my domains to have https://www.

Now i am using this:

 RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI}

But now when i go to www.example.com it redirects to https://www.www.example.com (twice www.)

http://example.com works perfect it redirects to https://www.example.com

回答1:

That's a normal behaviour.
Actually, you'll need to check if www is in the host or not before doing a redirect.

An easy way would be to split the problem in two conditions

RewriteEngine on

# redirect http://www.example.com to https://www.example.com
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# redirect http(s)://example.com to https://www.example.com
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


回答2:

You can use the following rule to redirect to https://www

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