Search code examples
apache.htaccessmod-rewriteurl-rewritingquery-string

Changing / replace multiple URL parameters with htaccess / mod_rewrite


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!


Solution

  • 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]