简体   繁体   中英

.htaccess rewrite with HTTP_HOST and QUERY_STRING

I would like to set up a redirect to a new host with query string. I am struggling to get the query added to the end of the target url. Here is my example old url

http://sub.oldexample.com/folder1/page1?value=ABC123

I would like it to go to

http://newexample.com/folder3/page6?value=ABC123

I do not have a problem when a query is not involved, for example the following code works perfectly but is unsuitable

RewriteCond %{HTTP_HOST} ^sub.oldexample.com$ 
RewriteRule ^folder1/([A-Za-z][A-Za-z][A-Za-z][0-9][0-9][0-9])$ http://newexample.com/folder3/$1 [L,R=301,NC]

I have tried to include a query condition but it fails

RewriteCond %{HTTP_HOST} ^sub.oldexample.com$ [NC]
RewriteCond %{QUERY_STRING} ^(value=ABC123)
RewriteRule ^$ http://newexample.com/folder3/page6?%1 [L,R=301,NC]

I find the following link a perfect environment for testing a .htaccess rule as it gives the output url that is generated

http://htaccess.madewithlove.be/

Following rule should work for you:

RewriteCond %{HTTP_HOST} ^sub\.oldexample\.com$ [NC]
RewriteCond %{QUERY_STRING} (^|&)value=ABC123(&|$) [NC]
RewriteRule ^folder1/page1/?$ http://newexample.com/folder3/page6 [L,R=301,NC]

You don't need to copy QUERY_STRING as it will be automatically carried over to new URL.

Try this:

RewriteCond %{HTTP_HOST} ^sub.oldexample.com$ [NC]
RewriteCond %{QUERY_STRING} (.+)=(.+)
RewriteRule ^/?folder1/page1$ http://newexample.com/folder3/page6 [QSA,R=301]

Just try to use the [QSA] flag.

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