13

I need to configure my reverse proxy so that the following parameter will be added at the end of the url: &locale=de-de

This almost works:

rewrite ^(.*)$ $1&locale=de-de break;

However, the problem is that I need to append '&locale=de-de' only if it isn't already there and if there is a '?' in the url...

Can I get some help on formulating the correct regex to do this?

Another question: Why is the question mark in my url not shown if I use this:
$uri?$args

Or $uri$is_args$args translates the url not encoded and the question mark is show as %3f.

Ideas?

EDIT: It seems that this behaviour exists while using in combination with proxy_pass. In a simple rewrite it works really well.

Sascha
  • 538
  • 2
  • 5
  • 12

3 Answers3

19
  1. In rewrite you match against URL's path part only. Which means, $1 will not contain the query string.
  2. By default, Nginx appends original query string to the rewrite replacement.

So, it should be safe to write

rewrite ^(.*)$ $1?locale=de-de break;

In the case you do not want Nginx to append the original query string, simply specify ? in the end of replacement URL:

rewrite ^(.*)$ $1?locale=de-de? break;
Alexander Azarov
  • 3,550
  • 21
  • 19
  • Thank you! I didn't see that I tried to do it the wrong way. – Sascha Sep 15 '11 at 21:07
  • There may be some way to get this working, but it doesn’t appear to be correct in general that nginx understands how to correctly concatenate query strings. When I tried it nginx was sending out `Location: https://site/?foo=bar?redirected_from=baz` which is very wrong. – andrew.n Apr 28 '21 at 16:27
  • If the original URL's query includes the parameter then it will be duplicated. – Luis Vazquez Sep 30 '21 at 02:43
3

The match for rewrite doesn't include the query params, so you need to test for that elsewhere.

Try:

if ($args !~* locale=de\-de){
    rewrite ^(.*)$ $1&locale=de-de last;
}
Shane Madden
  • 114,520
  • 13
  • 181
  • 251
3

The rewrite does not modify the request parameters, only the path portion of the URI. In my experience, messing with the rewrites leads to weird cycles, where the new parameter gets appended ad infinitum. Rewrite is probably not the way to do this in Nginx.

Instead, you should modify the $args variable using the set directive:

set $args $args&locale=de-de;
Palimondo
  • 141
  • 5