【问题标题】:Redirect all http/www into https://www将所有 http/www 重定向到 https://www
【发布时间】:2020-09-14 14:33:35
【问题描述】:

我有这个代码:

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

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案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]
    

    【讨论】:

      【解决方案2】:

      好的,我刚刚修好了。

      这是更新后的代码

      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]
      

      我可以保证这将在不超过 1 条链 的情况下进行 301 重定向。 我希望这可以帮助一些开发者!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-26
        • 2016-02-28
        • 1970-01-01
        • 2017-11-24
        • 2017-03-24
        • 2013-09-03
        • 1970-01-01
        • 2014-05-08
        相关资源
        最近更新 更多