上帝大脸 发表于 2018-11-14 09:34:01

nginx虚拟路径中proxy_pass对后端请求的影响

  假设nginx中的配置是这样的:
  server {
  listen 80;
  server_name x.x.x.x;
  . . . . . .
  location /subdir
  {
  proxy_pass http://y.y.y.y;
  }
  }
  那么,当用户请求http://x.x.x.x/subdir/other时,匹配到该区块,nginx反向代理到后端时会保留虚拟路径。nginx实际向后端发起的请求URL为http://y.y.y.y/subdir/other。
  假设nginx中的配置是这样的:
  server {
  listen 80;
  server_name x.x.x.x;
  . . . . . .
  location /subdir
  {
  proxy_pass http://y.y.y.y/;
  }
  }
  那么,当用户请求http://x.x.x.x/subdir/other时,匹配到该区块,由于proxy_pass中有指定后端URI路径,nginx代理请求到后端时不会保留虚拟路径。nginx实际向后端发起的请求URL为http://y.y.y.y//other。
  假设nginx中的配置是这样的:
  server {
  listen 80;
  server_name x.x.x.x;
  . . . . . .
  location /subdir
  {
  proxy_pass http://y.y.y.y/upstream_subdir;
  }
  }
  那么,当用户请求http://x.x.x.x/subdir/other时,匹配到该区块,由于proxy_pass中有指定后端URI路径,nginx代理请求到后端时不会保留虚拟路径。nginx实际向后端发起的请求URL为http://y.y.y.y/upstream_subdir/other。
  综合上述三个示例可以发现,问题的关键就在于proxy_pass指令中是否有指定后端服务器的URI,这决定了nginx代理请求到后端时是否会保留location中的虚拟路径。
  当将后端服务器写成upstream方式时,效果也是一样的。比如:
  upstream backend {
  server y.y.y.y:80;
  }
  server {
  listen 80;
  server_name x.x.x.x;
  . . . . . .
  location /subdir
  {
  proxy_pass http://backend/upstream_subdir;
  }
  }
  当用户请求http://x.x.x.x/subdir/other时,nginx实际向后端发起的请求URL仍然为http://y.y.y.y/upstream_subdir/other。

页: [1]
查看完整版本: nginx虚拟路径中proxy_pass对后端请求的影响