2009-05-04 29 views
20

我正在寻找重写多个子字符串的网址。一个子字符串被请求作为一个子目录,而另一个被请求作为正常的查询字符串参数。mod_rewrite规则匹配问号正则表达式

例如,我想从

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

重写URL到

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之后的任何参数。我该如何做到这一点?

回答

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

+0

感谢您的回答。工作得很好&我现在正在阅读食谱。 – markb 2009-05-05 12:56:55

+0

超级解决方案,它也适用于我,虽然我编辑了我的条件代码:RewriteRule ^([A-Za-z0-9 -_] +).php? pindex.php?typeofpage = $ 1 [QSA,L] – 2016-07-11 14:23:55

10

The 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设置为自动获取附加到新URL的原始请求查询即可。

+0

QSA有一个问题列在https://stackoverflow.com/questions/16468098/what-is-l-in-qsa-l-in-htaccess/16468677#comment79837245_16468677 。此外,rewritecond query_string无法区分含有查询字符串的请求,与使用裸体查询字符串的请求(即单个问号而没有其他字符)。有没有办法区分这两个请求? – Pacerier 2017-09-27 06:20:07

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 

将被改写的URL(如指定):

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