简体   繁体   中英

Common rewrite rule to append query to all the defined rewrite rules in htaccess

I want to redirect from old site urls to new site urls. I have many rules in htaccess files. See example below:

RewriteRule ^blog/one$ http://www.newsite.com/blog/x/ [R=301,L]
RewriteRule ^blog/two$ http://www.newsite.com/blog/y/ [R=301,L]
RewriteRule ^blog/three$ http://www.newsite.com/blog/z/ [R=301,L]
and so on..........

Redirection is working fine. Now I want to append a query string "?key=value&anotherKey=anotherValue" to all the destination urls. Is there a way to do this task by single line of code? Or do I need to append this query to all the urls one by one.

Here is an example that I want:

RewriteRule ^blog/one$ http:www.newsite.com/blog/x/?key=value&anotherKey=anotherValue [R=301,L]

EDITED: complete htaccess:

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /

#Custom redirection Starts form here

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^.*$ $0?key=value&anotherKey=anotherValue [L,NC]

#home page redirection
RewriteRule ^$ http://newsite.com/ [R=301,L]

#Blog Rewrite Rules
RewriteRule     ^blog/this-blog-is-included-for-redirection/?$ http://newsite.com/blog/ [R=301,L]

#Custom redirection ends here


RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

When I access this url: oldsite.com/blog/this-blog-is-included-for-redirection/

it redirects to: newsite.com/blog/?key=value&anotherKey=anotherValue

This is fine.

When I access this URL: oldsite.com/blog/this-blog-is-exluded-for-redirection/

it redirects to: oldsite.com/blog/this-blog-is-exluded-for-redirection/?key=value&anotherKey=anotherValue

Here I do not want to append the query.

You can keep a generic rule before your redirect rules to set the query string and redirect rules will automatically carry over query string to target URIs:

RewriteEngine On

# generic rule for query string
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^blog/(?:one|two|three)/?$ $0?key=value&anotherKey=anotherValue [L,NC]

RewriteRule ^blog/one/?$ http://www.newsite.com/blog/x/ [R=301,L,NC]
RewriteRule ^blog/two/?$ http://www.newsite.com/blog/y/ [R=301,L,nC]
RewriteRule ^blog/three/?$ http://www.newsite.com/blog/z/ [R=301,L,NC]

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