.htaccess redirect multiple urls to their corresponding new pages

a 夏天 提交于 2019-12-23 04:53:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!