Reverse proxy nginx to itself

Viewed 176

I am currently hosting a single-page react app that is hosted in the URL root like so:

server {
    listen       80;
    server_name  localhost;
    
    location / {
        root   /var/www/html;
        try_files $uri /index.html;
    }
}

I need to put the site behind an AWS elastic load balancer and at the same time change the path so everything is within a /support directory e.g. http://example.com/index.html -> http://example.com/support/index.html.

AWS ALBs do not support URL rewriting so I have to do this within the nginx config on the server. First of all I tried changing the config to:

server {
    listen       80;
    server_name  localhost;
    
    location /support {
        alias   /var/www/html;
        try_files $uri /index.html;
    }
}

This sort-of works but the URLs within the javascript content don't contain the /support path (e.g. they contain http://example.com/script.js instead of http://example.com/support/script.js).

I then tried creating a reverse-proxy config to proxy /support to /, which sadly put nginx in an infinite loop until it ran out of worker threads:

server {
    listen       80;
    server_name  localhost;
    
    location /support {
        proxy_pass http://localhost:80;
    }
    
    location / {
        root   /var/www/html;
        try_files $uri /index.html;
    }

}

I'm confused why requests are going into a reverse-proxy loop? Shouldn't proxy_pass remove the /support prefix before proxying the request, and therefore it shouldn't be "caught" again by the /support location?

1 Answers

Just a guess.

Do you want to serve something on /?

If not - it is easy:

server
{
    listen       80;
    server_name  localhost;
    
    location /support/
    {
        alias /var/www/html/;
        try_files $uri $uri/ /index.html;
    }
    
    location /
    {
        return 303 http://localhost/support$request_uri;
    }
}

Fiddle around with the ending slashes if it does not work (using them - or not - makes often a difference).

Use alias instead of root so that /support is not added to the /var/www/html folder.

Everything gets redirected to /support.


If you want to serve something on / which is different from /support:

Use sub_filter or subs_filter in /support to rewrite your source code links on-the-fly so that they will never use /.

If you have redirects inside your source code (or proxy_pass backend) - you need proxy_redirect and/or Lua to catch and change them on-the-fly.

Related