我如何preserve在mod_rewrite的规则,现有的查询字符串字符串、规则、preserve、mod_rewrite

2023-09-02 00:22:01 作者:快来亲亲我嘛

我想从改写一个网址:

http://domain.com/aa/whatever/whatever.php < BR> 到 http://domain.com/whatever/whatever.php?language=aa

http://domain.com/aa/whatever/whatever.php to http://domain.com/whatever/whatever.php?language=aa

然而,根据现有$ _GET变量,它或者是语言或安培;?。语言

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]

第二个按预期工作......第一个但永远不会打(它属于通过第二个正则表达式,它不打),即使正则表达式教练不告诉我,它应该。

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 在重写规则的模式匹配,对主机名和端口后的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.

要添加一个新的查询字符串参数语言= XX ,而preserving您需要使用QS​​A标志(查询字符串追加)任何现有的查询字符串。有了这个标志,只有一个规则,根据你的第二个案子应该足够了:

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]