Redirect existing file to different url using mod_

2019-08-20 02:16发布

问题:

I'm trying to use mod_rewrite to redirect an existing file to a different URL. I'm using the following and it has no effect. I've tried several variations of which don't work.

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]

Does it by chance have something to do with the url params?

回答1:

You cannot have query string in RewriteRule. RewriteRule matches only URL part that's why your new rule is not working. You need to have a separate RewriteCond to match QUERY string. It should be re-written like this:

# 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]