【问题标题】:Multiple R=301 redirect rules in .htaccess, single redirect.htaccess 中的多个 R=301 重定向规则,单个重定向
【发布时间】:2017-08-13 04:46:57
【问题描述】:

假设有两个重写规则我想通知浏览器:

  • 删除 www 前缀(http://www.example.orghttp://example.org
  • 删除 index.php(http://example.org/index.phphttp://example.org

我想同时应用这两个规则,并且我希望任何一个规则都导致 301 重定向。如果两个规则都匹配,我希望只有一个 301 重定向。

问题是,当一个规则有一个[R] 标志时,我还必须根据Apache documentation 指定一个[L](最后一个)标志来配合它。

您几乎总是希望将 [R] 与 [L] 结合使用(即使用 [R,L]),因为 [R] 标志本身会将 http://thishost[:thisport] 附加到 URI,但随后将此传递给规则集中的下一条规则,这通常会导致“请求中的 URI 无效”警告。

是否有任何变通方法可以让两个规则都不会导致 2 次重定向?

RewriteEngine On

# Naked domains
RewriteRule ^/?(.*)$ http://example.org/$1 [R=301,L]

# Remove index.php
RewriteRule ^index.php/(.*)$ /$1 [R=301,L]

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    不,L 标志是告诉重写过程停止处理可能遵循这些重写的新重写,但是由于您正在执行外部重定向,我怀疑没有它会导致问题。尽管如此,真正的重点是为什么您使用 mod_rewrite(或 .htaccess)来处理您的情况,因为它是如此简单(当没有更简单的选项时,应该保留 mod_rewrite)。

    这是正确的方式(没有 mod_rewrite)。

    #NameVirtualhost *:80 <- add and uncomment this only if your version is 2.2
    
    <Virtualhost *:80>
        ServerName example.org
        DocumentRoot /path/to/your/htdocs
        RedirectMatch 301 ^/index.php/(.*) /$1
    
        #other config
    </Virtualhost>
    
    <Virtualhost *:80>
        ServerName www.example.org
        Redirect 301 / http://example.org/
    </Virtualhost>
    

    【讨论】:

      【解决方案2】:
      RewriteEngine on
      
      RewriteCond %{HTTP_HOST} ^www\.(.*)
      RewriteRule ^.* - [E=A:http://%1]
      
      RewriteCond %{REQUEST_URI} ^/index.php
      RewriteRule ^index.php - [E=B:/]
      
      RewriteCond %{ENV:A} .+
      RewriteCond %{ENV:B} ^$
      RewriteRule ^(.*) - [E=B:/$1]
      
      RewriteCond %{ENV:A} .+ [OR]
      RewriteCond %{ENV:B} .+
      RewriteRule .* %{ENV:A}%{ENV:B} [R=301,L]
      

      【讨论】:

        猜你喜欢
        • 2010-12-22
        • 2011-01-05
        • 1970-01-01
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多