nginx如何配置upstream反向代理

nginx配置upstream反向代理

http {
 ...
 upstream tomcats {
  server 192.168.106.176 weight=1;
  server 192.168.106.177 weight=1;
 }

 server {
  location /ops-coffee/ { 
   proxy_pass http://tomcats;

   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加杠不加杠的陷阱,这里详细说下proxy_pass http://tomcats与proxy_pass http://tomcats/的区别:

虽然只是一个/的区别但结果确千差万别。分为以下两种情况:

1. 目标地址中不带uri(proxy_pass http://tomcats)。此时新的目标url中,匹配的uri部分不做修改,原来是什么就是什么。

location /ops-coffee/ {
 proxy_pass http://192.168.106.135:8181;
}

http://domain/ops-coffee/ -->  http://192.168.106.135:8181/ops-coffee/
http://domain/ops-coffee/action/abc -->  http://192.168.106.135:8181/ops-coffee/action/abc

2. 目标地址中带uri(proxy_pass http://tomcats/,/也是uri),此时新的目标url中,匹配的uri部分将会被修改为该参数中的uri。

location /ops-coffee/ {
 proxy_pass http://192.168.106.135:8181/;
}

http://domain/ops-coffee/ -->  http://192.168.106.135:8181
http://domain/ops-coffee/action/abc -->  http://192.168.106.135:8181/action/abc

以上就是nginx如何配置upstream反向代理的详细内容,更多请关注其它相关文章!