使用Nginx配置上的上游将位置的URL地址与服务器IP地址组成

问题描述:

我遇到的情况是,使用Tomcat在许多不同端口的不同机器上运行许多API. 我可以使用这些IP地址创建上游,但是在设置proxy_pass时如何将URL的另一部分添加到上游?

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?

上游:

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;
}

然后我在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;
}

如您所见,我必须添加此"login-api/auth",因为重定向地址上的实际URL地址为: http://10.2.54.8:8185/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

我该怎么做?

经过一番挖掘,我最终得到了以下解决方案:

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;
}

位置:

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;
}

然后在浏览器中调用:

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