Nginx howto correct the path from a back-end server redirect response under a virtual directory

directorynginxredirectvirtualization

The following was my deployed servers:

client —— nginx proxy(example.com) —— back-end server(192.168.1.20)

The nginx proxy's external URL was configured under a virtual directory http://example.com/demo/
The back-end server was configure to http://192.168.1.20:8080/

the following was part of the nginx configure file:

    location /demo {
            proxy_pass      http://192.168.1.20:8080/;
            proxy_redirect  default;
            proxy_set_header        Host            $http_host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    } 

When the back-end server send a redirect response (HTTP CODE 302) with LOCATION head field "http://192.168.1.20/subdir/", the nginx map this LOCATION header field to "http://example.com/subdir/", not the disired "http://example.com/demo/subdir/"

Best Answer

The backend app has to be aware of virtual hosting, like Zope virtual host monster and other solutions, basically it has to have a way to knowing that it is behind a virtual/proxied server and rewrite the internal URLs, rewrites and etc accordingly.

At least, the internal application has to write its rewrites and urls relative to the external path. In the example, the internal application is probably sending a redirect to /subdir instead of /demo/subdir.