How does Nginx reverse proxy multiple ports to different directories on the same port?

how do I configure the reverse proxy for Nginx to proxy multiple ports to different directories on the same port?

I have apps a, b, and c running on ports 8001, 8002, and 8003, respectively. The
server does not have a domain name configured, so the access addresses are ip:8001 , ip:8002 and ip:8003 .
now I want to implement it in Nginx, open only one port 80, and then access different services through different directories.
I expect the access address to become ip:80/a , ip:80/b and ip:80/c . And all resource requests under this application are based on this path.
such as ip:80/a can jump to ip:80/a/login instead of ip:80/login , notice the difference in the directory.
my / etc/nginx/conf.d/default.conf is as follows:

server {
    listen       80;
    server_name  localhost;
    location /a {
        proxy_pass http://127.0.0.1:8001/;
    }
    location /b {
        proxy_pass http://127.0.0.1:8002/;
    }
    location /c {
        proxy_pass http://127.0.0.1:8003/;
    }
}

according to my configuration above, enter ip:80/a to see that the application of ip:8001 has been successfully proxied. Just look at the home page and everything is normal.
but a jump to a multi-level directory such as ip:80/a/user/** fails and becomes ip:80/user/** .
I have also tried to follow the official documentation, using regular configuration of location or using rewrite, can not achieve the effect I want.
Thank you for your advice.


Map directories, and the backend of the agent must be changed accordingly, otherwise the relationship between directories cannot be maintained one by one. Rewrite also rewrites the url, and cannot rewrite the url of the a tag of the back-end page html. The loss outweighs the gain from a great deal of trouble.
A reasonable way is to use a second-level domain name to correspond to different backend services.

server {
        listen       80;
        server_name  sub1.example.com;
        location / {
                proxy_pass http://127.0.0.1:8001;
        }       
    }
    server {
        listen 80;
        server_name  sub2.example.com;
        location / {
               proxy_pass http://127.0.0.1:8002;
        }
    }
    ......

here's the problem: proxy_pass http://127.0.0.1:8001/;
this means absolute path, so he will ignore your / a
you change it to: proxy_pass http://127.0.0.1:8001;.
is fine. If the answer is right, then adopt


location and then change it to regular match


you'd better take a look at official website


I have tried, no, unless there is a domain name.


have you solved this problem? I am in the same situation as you now. I would like to ask for advice on how to solve it in the end.


can be solved with Module ngx_http_sub_module of Nginx, and pay attention to cancel gzip

when you need to reverse proxy.
Menu