避免登陆页面重定向 - 强制www和https

时间:2016-03-22 17:22:29

标签: php .htaccess

我正在尝试将非www转发到www并将http转发给https。我尝试了其他解决方案,我可以开始工作的唯一代码如下:

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

更新: (像@Croises所述) - 首先重定向www然后https

RewriteEngine on
### redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
### redirect non-http to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

2 个答案:

答案 0 :(得分:2)

在https:

之前重写域名
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

答案 1 :(得分:1)

您可以对重定向使用此单一规则:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+) [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301,NE]

在测试此更改之前清除浏览器缓存