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

标签 regex apache mod-rewrite query-string

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

/index.php?book=DesignPatterns&page=139
/index.php?book=Refactoring&page=285

使用mod_rewrite ,我怎样才能将它们重定向到这样的 SES URL?

/DesignPatterns/139
/Refactoring/285

最佳答案

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

因为RewriteRule只查看路径(直到但不包括问号),使用 RewriteCond捕获查询字符串中的值。

请注意,RewriteCond 中的匹配项在 %1 中捕获, %2 等,而不是 $1$2 等。

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

[L,R=301] 标志有两个作用:

  1. L 确保不会处理任何其他可能匹配的规则(换句话说,它确保这是处理的“最后一个”规则)。
  2. R=301 导致服务器发回重定向响应。 它不是重写,而是告诉客户端使用新的重试 网址。 =301 使其成为 permanent redirect ,这样,除其他外,搜索引擎就会知道在其索引中用新网址替换旧网址。

关于regex - 如何将查询字符串变量与 mod_rewrite 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2252238/

相关文章:

php - 将大写 html 标签转换为小写

python-2.7 - 需要一些帮助让 Apache 2.2.5 注册环境变量 (CentOS 6.10)

php - 在 MacOs Mojave 上找不到 XAMPP 的 httpd-xampp.conf 文件

windows - mod_rewrite 是否也适用于 Windows 服务器?

regex - 重写规则 : cannot compile regular expression - apache 2. 4.9

.htaccess - 301重定向2个域名指向同一个IP?

java - 正则表达式模式匹配除其中某些字符串之外的模式

php - 正则表达式匹配是否有硬性限制?

regex - 如何使用命令行从文件中选择列

apache - Hadoop HUE 时间线图表显示为灰色