匹配mod_rewrite规则正则表达式中的问号

时间:2009-05-04 22:32:54

标签: regex apache mod-rewrite

我希望用多个子字符串重写网址。一个子字符串被请求作为子目录,而其他任何子字符串都被请求作为普通的查询字符串参数。

例如,我想从

重写网址
http://www.mysite.com/mark/friends?page=2

http://www.mysite.com/friends.php?user=mark&page=2

除了问号字符外,我能够完成此操作。这是我的重写规则:

...
RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends[?]?([^/\.]+)?$ friends.php?user=$1&$2 [L]

如果我将问号更改为任何其他字符,则效果很好。似乎问题是'?'字符被错误地解释为新查询字符串的开头。

我需要传递/ user / friends之后出现的所有参数。我该如何做到这一点?

3 个答案:

答案 0 :(得分:33)

您应该使用[QSA]标志而不是尝试重写查询字符串。 [QSA]将查询字符串传递给重写的URL。

所以你的规则应该是这样的:

...
RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends/? friends.php?user=$1 [QSA,L]

您的案例与the example given for using the QSA flag in the mod_rewrite cookbook非常相似。

答案 1 :(得分:10)

query is not part of the URL path and thus cannot be processed with the RewriteRule directive。这只能通过RewriteCond指令完成(请参阅%{QUERY_STRING})。

as Chad Birch already said只需将QSA flag设置为自动将原始请求的查询附加到新网址即可。

答案 2 :(得分:1)

除了使用重写标志QSA之外,您还可以使用QUERY_STRING环境变量,如下所示:

RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9-_]+)/friends$ /friends.php?user=$1&%{QUERY_STRING}

有问题的网址

http://www.example.com/mark/friends?page=2

将被重写为(如指定):

http://www.example.com/friends.php?user=mark&page=2