Nginx proxy_pass is being ignored

load balancingnginxproxypass

I have an Nginx server which works as a proxy server.

I also have 3 different NodeJS Express servers running on ports 8080, 9090 and 8888 (all working correctly).

Servers 8080 and 9090 execute the same APP.
Server on 8888 currently should return 'POSTING' when the POST request has been forwarded.

Both GET and POST routes are set up correctly for server 8888 and I get a correct response if I call them directly with CURL requests:

import Express from 'express';
import BodyParser from 'body-parser';

// Initialise server
const server = Express();

// for parsing application/json
server.use(BodyParser.json());

// Setting port
server.set('port', 8888);

server.post('/', function(request, response) {

    console.log('POSTING');
    response.send('POSTING');
});

server.get('/', function(request, response) {

    console.log('GETTING');
    response.send('GETTING');
});

console.log(`Starting server on port ${server.get('port')}`)
server.listen(server.get('port'));

My Nginx config is the following:

upstream amit4got {

    server 127.0.0.1:8080;
    server 127.0.0.1:9090;
}

server {

    listen       7070;
    server_name  127.0.0.1;

    access_log  /usr/local/etc/nginx/logs/default.access.log;
    error_log  /usr/local/etc/nginx/logs/default.error.log;


    location /amit4got/ {

        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;

        proxy_pass              http://amit4got;
        proxy_read_timeout      90;
    }


    location /amit4got/flows {

        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;

        proxy_read_timeout      90;

        if ($request_method = POST) {

            proxy_pass          http://127.0.0.1:8888;
        }

        if ($request_method = GET) {

            proxy_pass          http://amit4got;
        }

     }
}

Nginx serves on port 7070, and for the endpoint /amit4got loads the content from either 8080 or 9090.

The problem is that when I try to POST to /amit4got/flows, there is no POST request to http://127.0.0.1:8888. I just get a response of 404 not found.

If I change the proxy_pass to a rewrite, then I get a correct response from the 8888 server.

if ($request_method = POST) {

    rewrite ^ http://127.0.0.1:8888;
}

I need to send through the POST params, so the rewrite does not work for me.

How can I make the proxy_pass to server 8888 work?

Thanks,
Amit

Best Answer

As mentioned in the comment:

proxy_pass http://127.0.0.1:8888; will end up posting to http://127.0.0.1:8888/amit4got/flows and not to http://127.0.0.1:8888/.