HTACCESS使用HTTPS重定向添加WWW

时间:2014-09-05 22:37:45

标签: apache .htaccess mod-rewrite redirect url-rewriting

目前我的htaccess代码是

#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. 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都不存在,则它不起作用,而是重定向到奇怪的网址

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

有什么建议?

1 个答案:

答案 0 :(得分:7)

用这个替换你当前的代码

RewriteEngine On

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

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