【问题标题】:Htaccess redirect from www to non-www, HTTP to HTTPS, and index.php to rootHtaccess 从 www 重定向到非 www,HTTP 重定向到 HTTPS,index.php 重定向到 root
【发布时间】:2020-07-19 15:15:39
【问题描述】:

我正在尝试重定向 url 变体,以便如下所示: http://www.example.com/index.php

简单地重定向到:https://example.com (即 http 到 https;www 到非 www;index.php 到域的根目录)

    # Canonical HTTPS/non-WWW
    <IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
    RewriteRule (.*) https://example/$1 [L,R=301]

    # direct /index.php to /
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/ 
    RewriteRule ^index\.php$ https://example.com/ [R=301,L] 
    </IfModule>

问题: 有没有更优雅的解决方案将两者结合起来?

【问题讨论】:

    标签: .htaccess redirect


    【解决方案1】:

    上面的从 www 重定向到 non-www 和从 HTTP 重定向到 HTTPS 的代码是正确的,并且总是会通过一次重定向将客户端传递到正确的地址。但是,在此之后将 /index.php 重定向到 / 可能会导致不必要的额外重定向。

    即。如果历史会这样发展:

    > http://www.example.com/index.php [301]
    > https://example.com/index.php [301]
    > https://example.com/ [200]
    

    您可以像这样简单地颠倒顺序来解决这个问题:

    <IfModule mod_rewrite.c>
    # direct /index.php to /
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
    RewriteRule ^ https://example/%1 [R=301,L]
    
    # Canonical HTTPS/non-WWW
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
    RewriteRule (.*) https://example/$1 [L,R=301]
    </IfModule>
    

    【讨论】:

    • 我尝试颠倒顺序,但结果 index.php 没有被删除。
    • 您在代码第 8 行使用的语法不正确 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/ 请尝试复制我的代码
    • 好的。我复制了您的代码并在另一个站点上进行了尝试。唯一的区别是我需要 www。这里。 index.php 拒绝消失。
    • 你用的是什么版本的apache?
    • 我更新了我的代码。请再试一次,告诉我进展如何