![](/img/trans.png)
[英]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.