【问题标题】:mod_rewrite to redirect URL with query stringmod_rewrite 使用查询字符串重定向 URL
【发布时间】:2012-11-29 15:49:41
【问题描述】:

我已经搜索了整个 stackoverflow,但似乎没有一个答案适用于这种情况。我的 httpd.conf 文件中已经有很多有效的 mod_rewrite 规则。我最近才发现 Google 已将我的一个未重写的 URL 编入索引,其中包含一个查询字符串:

http://domain.com/?state=arizona

我想使用 mod_rewrite 做一个 301 重定向到这个 URL:

http://domain.com/arizona

问题是稍后在我的重写规则中,第二个 URL 被重写以将查询变量传递给 WordPress。它最终被重写为:

http://domain.com/index.php?state=arizona

这是正确的功能。到目前为止,我所尝试的一切要么根本不起作用,要么让我陷入无休止的重写循环。这就是我现在所拥有的,它陷入了一个循环:

RewriteCond %{QUERY_STRING} state=arizona [NC]
RewriteRule .*   http://domain.com/arizona [R=301,L]
#older rewrite rule that passes query string based on URL:
RewriteRule ^([A-Za-z-]+)$ index.php?state=$1 [L]

这给了我一个无休止的重写循环并将我带到这个 URL: http://domain.com/arizona?state=arizona

然后我尝试了这个:

RewriteRule .*   http://domain.com/arizona? [R=301,L]

去掉了 URL 中的查询字符串,但仍然创建了一个循环。

【问题讨论】:

    标签: mod-rewrite query-string


    【解决方案1】:

    好的,添加第二个 RewriteCond 终于修复了它 - 现在可以正确重写并且没有循环:

    # redirect dynamic URL: ?state=arizona
    RewriteCond %{QUERY_STRING} state=arizona [NC]
    RewriteCond %{REQUEST_URI} ^/$ [NC]
    RewriteRule .*   http://domain.com/arizona? [R=301,L]
    # older rewrite rule that passes query string based on URL:
    RewriteRule ^([A-Za-z-]+)$ index.php?state=$1 [L]
    

    这是使它适用于任何州值的代码,而不仅仅是亚利桑那州:

    RewriteCond %{REQUEST_URI} ^/$ [NC]
    RewriteCond %{QUERY_STRING} ^state=([A-Za-z-]+)$ [NC]
    RewriteRule .*   http://domain.com/%1? [R=301,L]
    

    【讨论】:

      【解决方案2】:

      RewriteCond %{REQUEST_URI} ^/\?state=arizona$ [NC]

      应该是

      RewriteCond %{QUERY_STRING} state=arizona [NC]

      request_uri 结束于 ?令牌。

      【讨论】:

      • 您可能需要将RewriteRule ^([\w-]+)$ index.php?state=$1 [L] 收紧到RewriteRule ^([a-z_]+)$ index.php?state=$1 [L]。 index.php 不会匹配,也不会被重定向。
      • “点”字符如何匹配字符类 [\w-] ?无论如何,我在上面更改了它,但仍然有相同的循环。
      猜你喜欢
      • 1970-01-01
      • 2012-10-02
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多