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


Avoid landing page redirects - force www and https

我正在尝试将非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]

在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]

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

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]

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