【问题标题】:How to combine Apache redirects?如何结合 Apache 重定向?
【发布时间】:2012-11-23 23:41:21
【问题描述】:

我有一个 Apache 配置,它具有多个重写规则和重定向,以便获得最可爱的 URL,防止 SEO 重复等。这里有一个 sn-p 作为示例(它具有更多功能):

# Redirecting non-www to www 
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

# Removing index.php
RewriteCond %{REQUEST_URI} index\.php$ [NC]
RewriteRule .* / [R=301,L]

# A big bunch of these
Redirect permanent /old-article.html  http://www.example.com/new-article.html
Redirect permanent /another-old-article.html  http://www.example.com/new-article2.html

这很好用,但它碰巧会产生很多重定向。一个常见的情况是这样的:

http://example.com/index.php, 301 redirect to http://www.example.com/index.php
http://www.example.com/index.php, 301 redirect to http://www.example.com

有时会达到 4-5 个重定向。

现在,我希望将所有这些规则链接起来,只生成一个 301 重定向,如下所示:

http://example.com/index.php, 301 redirect to http://www.example.com

我知道我可以花一个下午的时间思考和整理规则以更好地匹配,而且我可以创建组合规则。但这会使已经很长的文件复杂化。我想要一个标志、操作数或任何可以执行所有规则的东西,就好像它们在内部一样,并且只有在爬取每条规则后才发出重定向。这甚至可能吗?

【问题讨论】:

    标签: apache mod-rewrite redirect url-rewriting


    【解决方案1】:

    似乎只要重新排序就可以得到你想要的:

    # A big bunch of these
    Redirect permanent /old-article.html  http://www.example.com/new-article.html
    Redirect permanent /another-old-article.html  http://www.example.com/new-article2.html
    
    # Removing index.php
    RewriteRule ^/index.php http://www.example.com/ [R=301,L]
    
    # Redirecting non-www to www 
    RewriteCond %{HTTP_HOST} ^example.com
    RewriteRule (.*) http://www.example.com/$1 [R=301,L]
    

    直接请求example.com域的旧文章:

    http://example.com/old-article.html
    

    将导致单个重定向到:

    http://www.example.com/new-article.html
    

    http://example.com/index.phphttp://www.example.com/index.php 的请求将导致单个重定向到:

    http://www.example.com/
    

    与其他任何内容都不匹配的请求将导致来自以下位置的单个重定向:

    http://example.com/foo
    

    收件人:

    http://www.example.com/foo
    

    这似乎涵盖了所有的基础。我错过了什么吗?

    【讨论】:

      【解决方案2】:

      从您的RewriteRules 中删除[L] 标志,它们将自动合并。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-30
        • 2012-06-19
        • 1970-01-01
        • 2014-07-18
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        相关资源
        最近更新 更多