Search code examples
.htaccessmod-rewrite

.htaccess replace url parameter value


I have a URL that with some parameters. One of the parameters called 'lang' and it looks like this:

https://example.com/example1/?id=1&lang=en

I want to redirect all the current URL with lang=en to lang=gb

https://example.com/example1/?id=1&lang=gb

Note: the example1 folder is an example and it doesn't a constant variable. every URL contains a different folder name.


Solution

  • This probably is what you are looking for:

    RewriteEngine on
    RewriteCond %{QUERY_STRING} ^(?:(.*&)?)lang=en(?:(&.*)?)$
    RewriteRule ^ %{REQUEST_URI}?%1lang=gb%2 [R=301]
    

    It is a good idea to start with a R=302 temporary redirection and only to change that to a R=301 permanent redirection once everything works as expected. That prevents nasty caching issues.

    In general you should prefer to implement such rules in the actual http server's host configuration. Distributed configuration files (".htaccess") should only be used if no other alternative exist. They come with a number of disadvantages.