【问题标题】:.htaccess: redirect to https without www results in loop.htaccess:重定向到 https 而没有 www 导致循环
【发布时间】:2017-04-17 12:45:58
【问题描述】:

我正在尝试将我的 URL 重定向到 https。我想做以下事情:

http://example.com => https://example.com 
http://www.example.com => https://example.com 
www.example.com => https://example.com 
example.com => https://example.com 

所以将每个 URL 转换为 https://example.com(去掉 www)!

我当前的 .htaccess 看起来像这样:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^example.com [NC] 
RewriteRule ^(.*)$ https://example.com /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png|\.ogg|\.wav|\.mp3|\.mp4|\.zip|\.pdf|\.fav|\.rar|\.doc)$ [NC]
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

我已经尝试添加

RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

在第一个 RewriteRule 之后和之前,但它会导致无限循环。 有人可以帮我吗?

【问题讨论】:

    标签: php .htaccess redirect https no-www


    【解决方案1】:

    将您的第一条规则更改为:

    # remove www and turn on https in same rule
    RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
    

    并在测试前清除浏览器缓存。

    【讨论】:

    • 我不知道为什么,但它仍然不起作用。不知何故,它导致了一个无限循环:/
    • 用于测试,注释掉所有其他规则并确保完全清除浏览器缓存。
    • 我找到了解决方案,我将在下面添加我的问题的答案
    • 我已经使用%{HTTP:X-Forwarded-Proto} 更新了我的答案,因为您似乎在代理后面。您仍然应该使用这条规则来删除 httpswww 而不是 2 条重定向规则(对 SEO 不利)
    【解决方案2】:

    我在这里找到了我的解决方案:

    https://serverfault.com/questions/677560/redirect-loop-when-forcing-https/678402#678402?newreg=f6df6f796eb343a5bbbe1da54c51f93b

    ### Force HTTPS
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2014-09-29
      • 2021-11-10
      • 2012-12-23
      • 2016-09-01
      相关资源
      最近更新 更多