使用mod_rewrite将现有文件重定向到不同的URL

时间:2012-02-06 04:33:44

标签: .htaccess mod-rewrite redirect url-rewriting

我正在尝试使用mod_rewrite将现有文件重定向到其他URL。我使用以下内容并没有效果。我尝试了几种不起作用的变体。

RewriteEngine on
AddHandler x-httpd-php .php3
# AddHandler x-httpd-php5 .php .php4

# This file exists, but this redirect doesn't work
RewriteRule ^show.php?id=review-1$ /review/1/super-baseball-2020/ [R=301,L]

它是否偶然与url params有关?

1 个答案:

答案 0 :(得分:0)

您不能在RewriteRule中拥有查询字符串。 RewriteRule仅匹配URL部分,这就是新规则不起作用的原因。你需要一个单独的RewriteCond来匹配QUERY字符串。它应该像这样重写:

# for external redirect from /shows.php?id=review-1 to /review/1/super-baseball-2020/
RewriteCond %{THE_REQUEST} ^GET\s/shows\.php\?
RewriteCond %{QUERY_STRING} (?:^|&)id=([^-]*)-(.*)(?:&|$) [NC]
RewriteRule ^ /%1/%2/super-baseball-2020/? [R=301,L,NC]

# for internal redirect from /review/1/super-baseball-2020/ to /shows.php?id=review-1
RewriteRule ^([a-z0-9]+)/([0-9]+)/([a-z0-9-]+)?/?$ shows.php?id=$1-$2 [L,NC,QSA]