'Proxy pass to a sub directory using nginx

I've got 2 Docker instances running, 1 being an SPA React app client and the other one is NodeJS api.

I want to setup Nginx on my Ubuntu server to handle requests based on the sub directory, so that we have requets going to example.com/$ go to the React App and that requests going to example.com/api/$ go to the NodeJS API.

I've setup the following on Nginx.. It's working 50%.. I cannot get the API side to work.

server {
    listen 80;

    server_name sub.example.com;

    #Client
    location / {
        proxy_pass http://localhost:49155/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    #API
    location ~ /api(.*)$ {
        proxy_pass http://localhost:49153/api$1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

}

The client side works fine, but I get 502 when making requests to /api. When I make a request directly to the server http://myServerIP:49153 (the API instance) it works fine.

Any suggestions?

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source