简体   繁体   中英

How to redirect a URL with a querystring

I've moved a website to a new domain and I've used RewriteRule to redirect a number of my URLs.

I'm stuck trying to redirect URLs with query strings in them?

RewriteRule  /news/archive.php?cat=economic-impact http://www.new-website.com/faqs/economic-impact [R=301,L]
RewriteRule /news/archive.php?cat=housing-need http://www.new-website.com/faqs/housing-need R=301,L]
RewriteRule /news/archive.php?cat=infrastructure http://www.new-website.com/faqs/infrastructure R=301,L]

Further up the htaccess file I'm using this to redirect the domain

RewriteEngine On
RewriteCond %{HTTP_HOST} ^old-website.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.old-website.com$
RewriteRule (.*)$ http://www.new-website.com/$1 [R=301]

When I visit:

old-website.com/news/archive.php?cat=economic-impact

it redirects to

new-website.com/news/archive.php?cat=economic-impact

Which 404s, I need to to redirect to:

new-website.com/faqs/economic-impact

Can anyone help?

You need to add a blank query string on your rewrite to truncate any existing query strings.

The below should do the job:

RewriteRule (.*)$ http://www.new-website.com/$1? [R=301]

In addition, the way you're checking the existing query strings won't work. You'll need to check them separately:

RewriteCond %{QUERY_STRING} "cat=(economic-impact|housing-need|infrasructure)"
RewriteRule news/archive.php http://www.new-website.com/faqs/%1? R=301,L]

The %1 will take a backreference from a regex group match in the RewriteCond

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