Nginx to rewrite based on a specific argument match

Raju Divakaran asked:

I am trying to achieve a redirection in nginx that should happen only if a specific argument and value pair is existing.

For example :

should be proxied to an application only if hjh=7484 is present in the request_uri. This can be anywhere in the whole URL, that said its position is not fixed.

If the incoming request against search page doesn’t have hjh=7484 the request should be redirected to

I have tried putting

    location ~* /search(.*)?hjh=7484(.*)?$ {
    proxy_pass $my_app;

Above is ending in 404.

2019/01/21 15:48:47 [error] 113#113: *109 open() “/usr/share/nginx/html/search” failed (2: No such file or directory),

If I change the above regex and allow any requests to search page to be passed its working!

My answer:

The location only matches the URI path component. It does not match query strings.

You can check the value of the argument instead, for instance:

location /search {
    if ($arg_hjh = 7484) {
        proxy_pass @my_app;
    # do something else

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.