Nginx proxy one port to multiple ports

nginxportPROXY

I have only one port opened in firewall and multiple services running. I want to redirect a request based on URI to different application. For example if I am accessing http:example.com:8443/test1 to be redirected to one application running on port 8440 and if am accessing http:example.com:8443/test1 to be redirected to the master nginx process running on port 80

My configuration file looks like this:

server {
    listen      127.0.0.1:8443;
    location  /test1{
        proxy_pass  http://127.0.0.1:8230;
    }
}
server {
    listen      127.0.0.1:8443;
    client_max_body_size 100m;
    location  /test2{
        proxy_pass  http://127.0.0.1:80; #Nginx master webserver port
    }
}

But when I am accessing localhost:8443/test2 I am receiving a 403 Forbidden but if I am the redirect port for test1 to 80 like this

server {
    listen      127.0.0.1:8443;
    location  /test1{
        proxy_pass  http://127.0.0.1:80;
    }
}

it's working.

Best Answer

You should only have 1 server since they are both listening on 127.0.0.1:8443. You would then have two location blocks inside that server, for example:

server {
    listen      127.0.0.1:8443;
    client_max_body_size 100m;

    location  /test1 {
        proxy_pass  http://127.0.0.1:8230;
    }


    location  /test2 {
        proxy_pass  http://127.0.0.1:80; #Nginx master webserver port
    }
}

Also, just be aware that you're proxying the traffic, rather than redirecting it. You will probably need a lot more configuration depending on how your applications are set up, since the /test2 will most likely be passed directly into your server on port 80 too.

Update: for PHP support, you'll need to make sure that php-fpm is installed, and will need a location block in your master nginx server, similar to:

location ~ \.php$ {
    proxy_pass http://your_ip_address:8080;
    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;
}