Search code examples
nginxurl-rewritingreverse-proxyproxypass

nginx proxy_pass omitting path


I have configured a nginx reverse proxy:

location / {
        root /var/www/html;
        index index.html;
}


location /login {
        proxy_pass http://127.0.0.1:9080;

        proxy_set_header        Host                    $host;
        proxy_set_header        X-Real-IP               $remote_addr;
}


location /app {
        rewrite ^/app/(.*)$ /$1 break;
        proxy_pass https://10.11.12.13/1020/;

        proxy_set_header        Host                    $host;
        proxy_set_header        X-Real-IP               $remote_addr;
}

The server listening on port 9080 redirects to the route /app/{generated subpath}. The server on IP 10.11.12.13 processes the request on {generated subpath}

Nginx doen't use the full path on the 10.11.12.13 upstream server, omitting the /1020/ endpoint. What could be the reason for this behaviour ?


Solution

  • The documentation states:

    When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break) ... In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

    So, you can either use a rewrite...break, for example:

    location /app {
        rewrite ^/app/(.*)$ /1020/$1 break;
        proxy_pass https://10.11.12.13;
        ...
    }
    

    Or, you can let the location and proxy_pass statements perform the same transformation, for example:

    location /app {
        proxy_pass https://10.11.12.13/1020;
        ...
    }
    

    Note that in this latter case, for correct transformation, both values should end with a / or neither end with a /.