简体   繁体   中英

htaccess - rewrite rule - redirect after url rewrite

This is pretty simple, but can't seem to figure this out.

I have a url /shows/index.php?id=1 that I wanted to appear in the url as /shows/1/index.php .

So I added this to my htaccess:

RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

This worked like a charm. I can now navigate to /shows/1/index.php no problem at all. However, I can also still navigate to /shows/index.php?id=1 . I wanted that page to automatically redirect to the new url, so I wrote this:

RewriteRule ^shows/index.php?id=([0-9]*)$ /shows/$1/index.php [R=301,L]

...but it doesn't do anything. However, if I do something like:

RewriteRule ^shows/([0-9]*)/0$ /shows/$1/index.php [R=301,L]

It redirects just fine. So that makes me think there is an issue with the first part of the rewrite rule, maybe? I'm not too familiar with this sort of stuff.

Since you want to redirect and rewrite the same request, you need to match against %{THE_REQUEST} variable otherwise you will get an infinite loop error on the redirect

 RewriteEngine on

# redirect /shows/index.php?id=1 to /shows/1/index.php
RewriteCond %{THE_REQUEST} /shows/index.php\?id=([^\s]+) [NC]
RewriteRule ^shows/index.php$ /shows/%1/index.php? [NC,L,R]
#rewrite /shows/1/index.php to /shows/index.php?id=1
RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

Clear your browser cache before testing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM