Make nginx reverse proxy 302 redirect to a URI sub-folder instead of root
I have a web server on my LAN with the URL https://10.0.0.22
and I am trying to access it from the internet through an nginx reverse proxy with a URL like https://domain.com/my/web/app
.
The difficulty I'm having is that the local server sends a 302 redirect to /login.php
, which nginx then passes back to the external client's browser to become https://domain.com/login.php
instead of https://domain.com/my/web/app/login.php
. This results in a 404 error because there's nothing at https://domain.com/login.php
.
I have tried many different options with little success, including a wide range of rewrite
, proxy_redirect
, and proxy_buffering
directives, but this is as close as I can get it:
location ^~ /my/web/app/
{
proxy_buffering off;
rewrite /my/web/app/(.*) /$1 break;
proxy_pass https://10.0.0.22/;
}
Is there a way to configure nginx so that the internal web server's 302 redirect to /login.php
manifests externally as /my/web/app/login.php
?
After continued investigation and testing of different combinations and ordering of directives, adding proxy_redirect
after the proxy_pass
directive seems to fix the URI translation issue:
proxy_redirect https://10.0.0.22/ https://domain.com/my/web/app/;
After some more tinkering, it seems that setting proxy_redirect
to default
does the same thing implicitly:
proxy_redirect default;
The full location block then looked like this:
location ^~ /my/web/app/
{
proxy_buffering off;
rewrite /my/web/app/(.*) /$1 break;
proxy_pass https://10.0.0.22/;
#proxy_redirect https://10.0.0.22/ https://domain.com/my/web/app/;
proxy_redirect default;
}
Images were still broken, however, because they point to /images
on the local server. I'm not sure of how to get nginx to translate those (because they're embedded in the HTML body) but to work around the problem for now, I was able to add a dedicated location
block for /images
before the location block for /my/web/app
, like this:
location ^~ /images/
{
proxy_pass https://10.0.0.22/images/;
proxy_redirect default;
}