我正在努力实现一个99%有效的东西,但有一个小问题。
假设我的动态网址是https://www.example.com/sample-page/
我希望所有以下URL变体重定向到具有301状态的活动URL。
http://example.com/sample-page/
http://www.example.com/sample-page/
https://example.com/sample-page/以上所有内容都应该重定向到https://www.example.com/sample-page/
通过使用下面显示的htaccess规则,我成功地实现了这一点。
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]上述规则的问题是:http://example.com/sample-page/执行双重重定向。
http://eyeacademy.com/expert-eye-examination/
301 Moved Permanently
https://eyeacademy.com/expert-eye-examination/
301 Moved Permanently
https://www.eyeacademy.com/expert-eye-examination/
200 OK如您所见,http重定向到https,然后https non-www重定向到https www。我一直在尝试对这条规则进行一些调整,并仔细阅读,但我相信这里有人会有一个更快、更健壮的解决方案?
发布于 2016-09-13 17:37:59
您可以使用此单个规则来重定向http -> https并添加www,并且无需在规则中硬编码主机名:
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301,NE]您还可以对现有规则进行重新排序,并避免像这样的多个重定向:
# first add www and make sure it is https://
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
# http -> https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]发布于 2016-09-13 17:32:44
在RewriteCond指令中使用or标志。将所有内容替换为以下内容:
RewriteCond %{HTTPS} off [NC,OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]https://stackoverflow.com/questions/39465734
复制相似问题