Home > other >  Changing / replace multiple URL parameters with htaccess / mod_rewrite
Changing / replace multiple URL parameters with htaccess / mod_rewrite

Time:06-03

I got this working snippet to change a query parameter:

RewriteCond %{QUERY_STRING}  (.*)&?name=(.*)? [NC]
RewriteRule ^pokladna/?$  $0?%1name_gls=%2 [R=301,L]

from here .htaccess rewrite rule with string replacement in url

But in my case I need to replace multiple query parameters.

For example: https://example.com/?utm_source=source&utm_medium=banner&utm_campaign=campaignname

needs to be https://example.com/?mtm_source=source&mtm_medium=banner&mtm_campaign=campaignname

There might be other parameters before, after or in between, which should not be affected.

Thank you!

CodePudding user response:

With your shown samples, attempts please try following htaccess rules file. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s/\?utm_source=([^&]*)&utm_medium=([^&]*)&utm_campaign=(\S )\s [NC]
RewriteRule ^ /\?mtm_source=%1&mtm_medium=%2&mtm_campaign=%3 [QSA,L]


Generic solution:

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s/\?(?:[^=]*)=([^&]*)&(?:[^=]*)=([^&]*)&(?:[^=]*)=(\S )\s [NC]
RewriteRule ^ /\?mtm_source=%1&mtm_medium=%2&mtm_campaign=%3 [QSA,L]

CodePudding user response:

Here is how you can replace multiple query parameters that start with utm_ to their counterparts that start with mtm_:

RewriteEngine On

# this rule will find any of the 3 utm_ query parameters and will
# replace each with the mtm_ query parameter. N flag is used here to 
# make this rule loop until all query parameters have been replaced
# in the end it sets an env variable MTM to 1
RewriteCond %{QUERY_STRING} ^(.*&)?u(tm_(?:source|medium|campaign)=[^&]*)(&.*)?$ [NC]
RewriteRule ^ %{REQUEST_URI}?%1m%2%3 [N,DPI,E=MTM:1]

# if env variable MTM is 1 then do an external redirect
RewriteCond %{ENV:MTM} =1
RewriteRule ^ %{REQUEST_URI} [L,R=302,NE]

# other rules go below this line

Once satisfied with the result replace 302 with 301 (permanent redirect).

This needs to be tested on a local Apache web server not on any online test facility.

  • Related