Search code examples
regex.htaccessurl-rewriting

.htaccess redirect for url with parameters


I have searched around for this but not finding what I need. Basically any url which has ? at the end followed by further characters should be redirected to another url, the same path excluding the language though. An example will make it clearer.

If a user lands on https://example.com/fr/contact-us/?utm_medium=email

they should be redirected to https://example.com/contact-us/?utm_medium=email

and that should be the case for any url with ? in it after the last /

Unfortunately I don't know that much about redirects so I don't have a great attempt here.

RewriteCond %{QUERY_STRING} ^utm_medium=\d+$
RewriteRule ..... [R=301]

Solution

  • Basically any url which has ? at the end followed by further characters should be redirected to another url, the same path excluding the language though.

    You may use this redirect rule:

    RewriteCond %{QUERY_STRING} .
    RewriteRule ^[a-z]{2}/(.*) /$1 [L,NE,R=301]
    

    Here:

    • %{QUERY_STRING} . makes sure there is non-empty query string
    • [a-z]{2}/ matches any 2 letter language code followed by a /
    • Query string is automatically copied over to the target URL.