【问题标题】:htaccess RewriteRule page with query string带有查询字符串的 htaccess RewriteRule 页面
【发布时间】:2013-12-21 10:18:40
【问题描述】:

我有一组试图重定向到新 URL 的页面。它们在目标 URL 中的查询字符串与在原始 URL 中的查询字符串不同。

http://localhost/people.php?who=a

应该重定向到:

http://localhost/people/?t=leadership

不断……

我有以下一组重写规则,显然做错了什么。

RewriteRule ^people.php?who=a /people/?t=leadership [R=301,L]
RewriteRule ^people.php?who=f /people/?t=faculty [R=301,L]
RewriteRule ^people.php?who=p /people/?t=students [R=301,L]
RewriteRule ^people.php?who=r /people/ [R=301,L]
RewriteRule ^people.php /people/ [R=301,L]

发生的情况是前 4 条规则不匹配,页面重定向到:

http://localhost/people/?who=a

我尝试了 QSD 标志,但似乎我的问题是该规则与整个查询字符串不匹配,而不是它正在传递查询字符串。

【问题讨论】:

    标签: apache .htaccess mod-rewrite redirect


    【解决方案1】:

    您需要匹配%{QUERY_STRING} 变量。查询字符串不是 RewriteRule 中匹配的一部分:

    RewriteCond %{QUERY_STRING} ^who=a$
    RewriteRule ^people.php$ /people/?t=leadership [R=301,L]
    RewriteCond %{QUERY_STRING} ^who=f$
    RewriteRule ^people.php$ /people/?t=faculty [R=301,L]
    RewriteCond %{QUERY_STRING} ^who=p$
    RewriteRule ^people.php$ /people/?t=students [R=301,L]
    RewriteCond %{QUERY_STRING} ^who=r$
    RewriteRule ^people.php$ /people/ [R=301,L]
    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^people.php$ /people/ [R=301,L]
    

    【讨论】:

    • 太棒了。我知道这是我所缺少的非常基本的东西。由于没有查询字符串,是否需要最后一个 RewriteCond?此外,看起来 RewriteRules 中有一些拼写错误,您遗漏了 ?在 $ 之前并在第 4 行留下了一个流浪 f。我尝试编辑,但它少于 6 个字符,所以 stackoverflow 不会让我。
    • @isabisa 最后一个条件只是一个预防措施,如果没有查询字符串,那么它将匹配^$,它是空白的。我删除了错别字。
    • 请注意,^who=a$ 带有“句子”结尾和开头标记将只匹配 ?who=a – 既不匹配 ?other=e&who=a 也不匹配 ?who=a&other=e
    【解决方案2】:

    您无法在 RewruteRule URI 模式中匹配 QUERY_STRING

    试试这样的规则:

    RewriteCond %{THE_REQUEST} \s/+people\.php\?who=a\s [NC]
    RewriteRule ^ /people/?t=leadership [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/+people\.php\?who=f\s [NC]
    RewriteRule ^ /people/?t=faculty [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/+people\.php\?who=p\s [NC]
    RewriteRule ^ /people/?t=students [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/+people\.php(\?who=r)?\s [NC]
    RewriteRule ^ /people/? [R=301,L]
    

    【讨论】:

      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2022-03-22
      • 2020-12-14
      • 2018-07-25
      • 2014-08-01
      • 2015-05-18
      相关资源
      最近更新 更多