[英]Redirect all non-www to www for both http and https with .htaccess
[英]Redirect all http/www into https://www
我有这个代码:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
它的作用是:
http://example.com
它重定向到https://www.example.com
(这是正确的)https://example.com
它重定向到https://www.example.com
(这是正确的)http://www.example.com
它不会重定向到https://www.example.com
。 请注意,它需要不超过 1 个链。 它应该重定向到https://www.example.com
。
好的,我刚修好了。
这是更新的代码
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
我可以保证这将全部执行 301 重定向,而不会超过1 个链。 我希望这可以帮助一些开发人员!
您可以避免对主机名进行硬编码,并在单个重定向规则中执行这两个条件,如下所示:
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.