关于apache:HTACCESS通过HTTPS重定向添加WWW

HTACCESS add WWW with HTTPS redirect

当前我的htaccess代码是

1
2
3
4
5
6
7
8
#add www
RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]


#send all traffic to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

这在输入以下网址时有效

1
2
3
4
5
6
1. https://example.com -> https://www.example.com
2. http://example.com -> https://www.example.com
3. http://www.example.com -> https://www.example.com
4. https://example.com -> https://www.example.com
5. https://example.com/somepage -> https://www.example.com/somepage
6. http://www.example.com/somepage -> https://www.example.com/somepage

但是当尝试访问某些页面时,如果同时不存在https和www时,它将不起作用,而是重定向到奇怪的url

1
7. http://example.com/somepage -> https://www.example.com/https://example.com/somepage


用此代码替换当前代码

1
2
3
4
5
RewriteEngine On

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

注意:也许您必须清除浏览器的缓存才能看到它适用于http://example.com/somepage