【问题标题】:Match Question Mark in mod_rewrite rule regex在 mod_rewrite 规则正则表达式中匹配问号
【发布时间】:2010-10-23 18:32:35
【问题描述】:

我希望用多个子字符串重写 url。一个子字符串被请求为子目录,而任何其他子字符串被请求为正常的查询字符串参数。

例如,我想重写 url 从

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

【问题讨论】:

    标签: regex apache mod-rewrite


    【解决方案1】:

    您应该使用[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非常相似。

    【讨论】:

    • 感谢您的回答。效果很好,我现在正在阅读食谱。
    • 超级解决方案它也对我有用,尽管我根据我的条件编辑了代码:RewriteRule ^([A-Za-z0-9-_]+)\.php? pindex.php?typeofpage=$1 [QSA,L]
    【解决方案2】:

    除了使用重写标志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
    

    【讨论】:

      【解决方案3】:

      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 的原始请求查询。

      【讨论】:

      • QSA 在stackoverflow.com/questions/16468098/… 中列出了一个问题。此外,rewritecond query_string 无法区分没有查询字符串的请求和带有裸查询字符串的请求(即一个问号,没有别的)。有没有办法区分这两个请求?
      • 好的 nbm.. 我找到了:${the_request}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多