【问题标题】:.htaccess redirect both naked http and https to www https.htaccess 将裸 http 和 https 重定向到 www https
【发布时间】:2016-11-08 17:13:34
【问题描述】:

我的一个域有类似的问题。我为裸域和 www 域都安装了 SSL 证书。

现在,但是我想将裸 http://domain.com 和 https://domain.com 都重定向到 https://www.domain.com。

我的 .htaccess 中有此规则,但它涵盖了当您使用 https://domain.com 显式访问站点时的重定向,但是,当访问 http://domain.com 时,它会重定向到 http://www.domain.com 而不是 https://www.domain.com。

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

【问题讨论】:

    标签: apache .htaccess redirect mod-rewrite


    【解决方案1】:

    我个人会这样布局,这将强制使用 WWW 和 HTTPS。

    RewriteEngine On
    
    #Force WWW on everything
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    
    #Force HTTPS on everything
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    

    【讨论】:

    • 如果 URL 是 http://example.com,那么这个 sn-p 将执行两次重定向,这对性能或 SEO 都不利
    • 一直在学习,感谢您的意见@anubhava。将不得不改变我前进的方法:P
    • 在第一条规则上使用 https 可以避免双重重定向。切勿使用 R=301 进行测试。
    【解决方案2】:

    你应该用这个规则替换你现有的规则:

    RewriteEngine On
    
    # add www and convert http to https
    RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
    

    将此规则保留在RewriteEngine On 行的正下方,并在测试前清除浏览器缓存。

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 2015-02-16
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      相关资源
      最近更新 更多