apache 在 mod_rewrite 规则正则表达式中匹配问号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/822421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match Question Mark in mod_rewrite rule regex
提问by markb
I am looking to rewrite urls with multiple substrings. One substring is being requested as a subdirectory, while any others are requested as normal query string parameters.
我希望用多个子字符串重写 url。一个子字符串作为子目录被请求,而任何其他子字符串作为普通查询字符串参数被请求。
For example, I would like to rewrite urls from
例如,我想从
http://www.mysite.com/mark/friends?page=2
to
到
http://www.mysite.com/friends.php?user=mark&page=2
I am able to accomplish this with the exception of the question mark character. Here is my rewrite rule:
除了问号字符外,我能够完成此操作。这是我的重写规则:
...
RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends[?]?([^/\.]+)?$ friends.php?user=& [L]
If I change the question mark to any other character it works great. It seems like the problem is that the '?' character is being interpreted incorrectly as the start of a new query string.
如果我将问号更改为任何其他字符,则效果很好。似乎问题在于“?” 字符被错误地解释为新查询字符串的开始。
I need to pass on any parameters that appear after /user/friends as is. How do I accomplish this?
我需要按原样传递出现在 /user/friends 之后的任何参数。我该如何实现?
回答by Chad Birch
You should be using the [QSA]flag instead of trying to rewrite the query string. [QSA]passes on the query string to the rewritten URL.
您应该使用该[QSA]标志而不是尝试重写查询字符串。[QSA]将查询字符串传递给重写的 URL。
So your rule should look like:
所以你的规则应该是这样的:
...
RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends/? friends.php?user= [QSA,L]
Your case is very similar to the example given for using the QSA flag in the mod_rewrite cookbook.
您的情况与在 mod_rewrite cookbook 中使用 QSA 标志给出的示例非常相似。
回答by Gumbo
The query is not part of the URL path and thus cannot be processed with the RewriteRuledirective. This can only be done with the RewriteConddirective (see %{QUERY_STRING}).
该查询不是URL路径的一部分,因此不能与被处理RewriteRule的指令。这只能通过RewriteCond指令来完成(请参阅 参考资料%{QUERY_STRING})。
But as Chad Birch already saidit suffices th set the QSAflagto automatically get the original requested query appended to the new URL.
但是正如 Chad Birch 已经说过的那样,设置QSA标志以自动获取附加到新 URL 的原始请求查询就足够了。
回答by Yuci
In addition to using the rewrite flag QSA, you can also use the QUERY_STRING environment variable as shown below:
除了使用重写标志 QSA 之外,您还可以使用 QUERY_STRING 环境变量,如下所示:
RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends$ /friends.php?user=&%{QUERY_STRING}
And the URL in question
和有问题的网址
http://www.example.com/mark/friends?page=2
will be rewritten to (as specified):
将被重写为(如指定):
http://www.example.com/friends.php?user=mark&page=2

