Compose URL address on the location with the server IP address using upstream on Nginx configuration

巧了我就是萌 提交于 2020-04-18 00:50:08

问题


I have this situation where a have lots of API´s running on different machines on different ports using Tomcat. I can create the upstream with those IP addresses but how to add the other part of the URL to the upstream when setting the proxy_pass?

The upstream:

upstream login_api_stream {
   least_conn; 
   server 10.2.54.8:8185;
   server 10.2.54.8:8285;
   server 10.2.54.8:8385;
   server 10.2.54.9:8085 backup;
}

Then I create the location inside http:

location /login-api/ {
    add_header X-Real-IP $remote_addr;
    add_header X-Forwarded-For $proxy_add_x_forwarded_for;
    add_header X-Forwarded-Proto $http_x_forwarded_proto;
    # I have to add "login-api/auth" on the upstream
    proxy_pass http://login_api_stream/login-api/auth;
}

As you can see I must add this "login-api/auth" because the real URL address on the redirected address is: http://10.2.54.8:8185/login-api/auth

How can I do that?


回答1:


After some digging I ended up with this solution:

The upstream (important to notice, you cannot use this sign _ in the name of the upstream):

upstream newlogin {
   least_conn; 
   server 10.2.54.8:8085;
   server 10.2.54.8:8285;
   server 10.2.54.8:8185;
   server 10.2.54.9:8085 backup;
}

The location:

location ~ ^/login-api/auth/ {
    add_header Host $host;
    add_header X-Real-IP $remote_addr;
    add_header X-Forwarded-For $proxy_add_x_forwarded_for;
    add_header X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_pass http://newlogin$uri$is_args$args;
}

And then in browser I call:

http://MyNginxDomain/login-api/auth/


来源:https://stackoverflow.com/questions/60950567/compose-url-address-on-the-location-with-the-server-ip-address-using-upstream-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!