问题描述
我正在尝试重写以下网址:
I'm trying to rewrite an url from:
http://domain.com/aa/whatever/whatever.php
到
http://domain.com/whatever/whatever.php?language=aa
但是,根据现有的 $_GET 变量,它必须是 ?language 或 &language.
However, depending on existing $_GET variables, it either has to be ?language or &language.
为此,我使用了 2 个带有 [L] 标志的正则表达式:
To do this, I use 2 regexes with the [L] flag:
RewriteRule ^([a-z]{2})/(.*.php?.*) /$2&language=$1 [L]
RewriteRule ^([a-z]{2})/(.*) /$2?language=$1 [L]
第二个按预期工作......然而,第一个从未被命中(它落入第二个正则表达式,它确实命中了),即使 Regex Coach 确实向我展示了它应该.
The second one works as expected... The first one however is never hit (it falls through to the second regex, which does hit), even though Regex Coach does show me that it should.
如果刚刚读到我需要使用两个反斜杠来转义问号.如果我这样做,它确实会命中第一个正则表达式,但永远不会找到其他 GET 变量.
If just read that I need to use two backslashes to escape the question mark. If I do this, it does hit on the first regex but never find the other GET variables.
推荐答案
来自 mod_rewrite 的文档 RewriteRule 中的模式与主机名和端口之后和查询字符串之前的 URL 部分匹配,因此不包括查询字符串.这就是为什么你没有得到其他变量的原因.
From the documentation for mod_rewrite the pattern in RewriteRule matches against the part of the URL after the hostname and port, and before the query string so the query string is not included. That is why you don't get the other variables.
要添加新的查询字符串参数 language=xx
同时保留任何现有的查询字符串,您需要使用 QSA 标志(查询字符串附加).有了这个标志,基于你的第二种情况的一条规则就足够了:
To add a new query string parameter language=xx
whilst preserving any existing query string you need to use the QSA flag (query string append). With this flag, just one rule based on your second case should be sufficient:
RewriteRule ^([a-z]{2})/(.*) /$2?language=$1 [QSA]
这篇关于如何在 mod_rewrite 规则中保留现有的查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!