1

Ngnix newbie here. Please I need some help to figure out how to correctly make nginx modify and redirect (proxy?) incoming requests. The redirection seems to work ok, but the URL is not rewritten at the destination.

My configuration is:

        server {

       listen 91 default_server ssl;

       ssl_prefer_server_ciphers on;
       ssl_certificate /etc/nginx/ssl/domain.crt;
       ssl_certificate_key /etc/nginx/ssl/domain.key;

        location /dest {

        rewrite ^a_service_prod&id_number=((1234701|1234708|1234802|1234808|1234812|1234902)\d+)&(.*?)$ /dest?service=a_service_prod.sub_service&operation=sub_service&id_number=$1&$2 break;
            proxy_pass http://192.168.1.1:1440;
            proxy_redirect off;
            proxy_set_header Host $host;
        }
    }

Im trying to get requests such as /dest?service=a_service_prod&id_number=12347016734696&slime=somethig to be rewritten and the request sent to another server as http://192.168.1.1:1440/dest?service=a_service_prod.sub_service&operation=sub_service&id_number=12347016734696&slime=somethig

But instead at the destination, what is received is http://192.168.1.1:1440/dest?service=a_service_prod&id_number=12347016734696&slime=somethig

Please what am I doing wrong, and how can I fix it?

3

You current method does not work because you are attempting to capture the query string in the regular expression of a rewrite directive. nginx uses a normalized URI for evaluating rewrite and location directives, which does not include the ? and anything that follows it.

You can find the query string in the $request_uri variable, the $args variable - or split up amongst the $arg_xxx variables. See this document for details.

You can apply a regular expression to one of those variables by using an if statement or a map directive.

The example below uses a map directive (see this document for details) with a regular expression and two named captures to reconstruct your required argument list. The upstream URI is appended to the proxy_pass directive (see this document for details).

map $args $newargs {
    default $args;
    ~*^(?<prefix>service=a_service_prod)&(?<suffix>id_number=(?:1234701|1234708|1234802|1234808|1234812|1234902)\d+&.*)$  $prefix.sub_service&operation=sub_service&$suffix;
}
server {
    ...
    location /dest {
        proxy_pass http://192.168.1.1:1440$uri?$newargs;
        ...
    }
}
  • Thank you very much, this is very valuable information. I ended up using if statements, because I had multiple groupings of id_number=([:digits:]) that needed to go to different rewrites, and also because I am still trying to understand map. – SinaOwolabi May 21 '18 at 21:52

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.