问题
I'd like to redirect the following urls with .htaccess:
/books/garden to /garden-books
/movies/dvd-comedy to /dvd/comedy
/music-soundtracks/new to /music/soundtracks
Anyone know how to do this?
回答1:
If you want an even simpler solution you can also try this:
Redirect 301 /books/garden /garden-books
Redirect 301 /movies/dvd-comedy /dvd/comedy
Redirect 301 /music-soundtracks/new /music/soundtracks
The old url is first after "Redirect 301", then the new url.
回答2:
Add this to your .htaccess file in your site's root directory.
RewriteEngine On
RewriteCond %{THE_REQUEST} \ /+(books)/(garden)\s [NC]
RewriteRule ^ /%2-%1 [R=301,L]
RewriteRule ^(garden)-(books)/?$ /$2/$1 [NC,L]
RewriteCond %{THE_REQUEST} \ /+movies/(dvd)-(comedy)/?[\s?] [NC]
RewriteRule ^ /%1/%2 [R=301,L]
RewriteRule ^(dvd)/(comedy)/?$ /movies/$1-$2 [NC,L]
RewriteCond %{THE_REQUEST} \ /+(music)-(soundtracks)/new/?[\s?] [NC]
RewriteRule ^ /%1/%2 [R=301,L]
RewriteRule ^(music)/(soundtracks)/?$ /$1-$2/new [NC,L]
Yes, it's possible but you need to consider this: if your actual URL is, say, /page.php?var=val
, and your pretty URL is /page/var/val
, then the above rules make sure that not only the pretty version /page/var/val
works, but if someone tries to access that actual /page.php?var=val
they are redirected back to /page/var/val
as well.
So, if you're only interested in resolving the pretty URLs, you can use only the following.
RewriteEngine On
RewriteRule ^(garden)-(books)/?$ /$2/$1 [NC,L]
RewriteRule ^(dvd)/(comedy)/?$ /movies/$1-$2 [NC,L]
RewriteRule ^(music)/(soundtracks)/?$ /$1-$2/new [NC,L]
来源:https://stackoverflow.com/questions/28484170/htaccess-redirect-multiple-urls-to-their-corresponding-new-pages