简体   繁体   English

将所有 http/www 重定向到 https://www

[英]Redirect all http/www into https://www

I have this code:我有这个代码:

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]

What this does is:它的作用是:

  • With http://example.com it redirects to https://www.example.com (this is correct)使用http://example.com它重定向到https://www.example.com (这是正确的)
  • With https://example.com it redirects to https://www.example.com (this is correct)使用https://example.com它重定向到https://www.example.com (这是正确的)
  • But with http://www.example.com it doesn't redirect to https://www.example.com .但是对于http://www.example.com它不会重定向到https://www.example.com

Please take note that It needs to be not more than 1 chain.请注意,它需要不超过 1 个链。 It should redirect to https://www.example.com .它应该重定向到https://www.example.com

Okay I just fixed it.好的,我刚修好了。

this is the updated code这是更新的代码

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]

I can guarantee that this will all do 301 redirect without more than 1 chain .我可以保证这将全部执行 301 重定向,而不会超过1 个链 I hope this helps some developers out there!.我希望这可以帮助一些开发人员!

You can avoid hardcoding your host name and do both conditions in a single redirect rule like this:您可以避免对主机名进行硬编码,并在单个重定向规则中执行这两个条件,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM