如何将查询字符串变量与mod_rewrite匹配?

Pat*_*ney 46 regex apache mod-rewrite query-string

假设我有带有查询字符串参数的URL,如下所示:

/index.php?book=DesignPatterns&page=139
/index.php?book=Refactoring&page=285
Run Code Online (Sandbox Code Playgroud)

使用mod_rewrite,如何将它们重定向到这些SES URL?

/DesignPatterns/139
/Refactoring/285
Run Code Online (Sandbox Code Playgroud)

Pat*_*ney 103

RewriteCond %{QUERY_STRING} book=(\w+)&page=(\d+)  
RewriteRule ^index.php /%1/%2? [L,R=301]
Run Code Online (Sandbox Code Playgroud)

因为RewriteRule只查看路径(最多但不包括问号),所以使用RewriteCond捕获查询字符串中的值.

需要注意的是,从比赛RewriteCond被捕获的%1, %2等等,而不是$1,$2等等.

另请注意最后?的结尾RewriteRule.它告诉mod_rewrite不要将原始查询字符串附加到新URL,因此最终会得到 /DesignPatterns/151intead /DesignPatterns/151?book=DesignPatterns&page=151.

[L,R=301]标志做两件事情:

  1. L 确保不会处理其他可能匹配的规则(换句话说,它确保这是处理的"最后"规则).
  2. R=301导致服务器发回重定向响应.它不是重写,而是告诉客户端再次使用新URL.将=301使其成为一个永久重定向,这样,除其他事项外,搜索引擎会知道在他们的指数新的URL,以取代旧的URL.

  • +1当我给出答案的完整解释时,我喜欢它 (12认同)
  • 要不将原始查询字符串附加到新URL,请使用`[QSD]`标志(http://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsd) (5认同)