您的示例中有一些不正确的地方:
- 您不能检查
RewriteRule 中的查询字符串,只能在RewriteCond 中检查
- 您的
RewriteRule 行是向后的 - 第一部分是 URL 的正则表达式匹配,第二部分是您想要的。
- 您需要将
[R] 规则作为重写的一部分来执行重定向,否则它只会“重写”服务器看到的 URL 而不会更改实际 URL。
这是您第一次重写的示例,将/page.php?page=foo 重定向到/foo。您首先需要一个RewriteCond 来检查%{QUERY_STRING} 变量以查看其中是否包含page=...。我们可以使用字符匹配 ([^&]*) 来获取所有不是 & 符号的字符并存储在匹配组中。接下来我们为page.php 执行RewriteRule(请注意,我们不需要前导/,因为RewriteBase 并且. 已转义)。如果此处有匹配项,您希望从 RewriteCond 重定向到匹配组 - 它使用 %1 而不是 $1 引用,就像它来自 RewriteRule 一样。您还需要在重定向的末尾附加一个?,它告诉Apache 删除查询字符串,这样您就不会以/foo?page=foo 结尾。最后,您将需要[R=301] 来执行 HTTP 状态代码为 301 的重定向。[L] 表示这是 Last 规则,如果有匹配项则要处理。
RewriteEngine On
RewriteBase /
# page.php?page=about to about
RewriteCond %{QUERY_STRING} page=([^&]*) [NC]
RewriteRule page\.php /%1? [R=301,L]
您的第二次重写更接近,但与第一次一样,逻辑是倒退的。您希望第一部分匹配*.php,然后第二部分表示重定向到/$1。同样,您将需要 [R-301] 进行重定向。
# something.php to something
RewriteRule (.*)\.php$ $1 [R=301,L]
您可以在 http://htaccess.madewithlove.be/ 上进行测试。
使用http://example.com/page.php?page=foo,重定向到http://example.com/foo
1 RewriteEngine On
2 RewriteBase /
3 # page.php?page=about to about
4 RewriteCond %{QUERY_STRING} page=([^&]*) [NC]
This condition was met
5 RewriteRule page\.php /%1? [R=301,L]
This rule was met, the new url is http://example.com/foo
Test are stopped, because of the R in your RewriteRule options.
A redirect will be made with status code 301
使用http://example.com/foo.php 重定向到http://example.com/foo
1 RewriteEngine On
2 RewriteBase /
3 # page.php?page=about to about
4 RewriteCond %{QUERY_STRING} page=([^&]*) [NC]
This condition was not met
5 RewriteRule page\.php /%1? [R=301,L]
This rule was not met because one of the conditions was not met
6 # something.php to something
7 RewriteRule (.*)\.php$ /$1 [R=301,L]
This rule was met, the new url is http://example.com/foo
Test are stopped, because of the R in your RewriteRule options.
A redirect will be made with status code 301