一 实验环境

   URL的一般语法格式为:protocol :// hostname[:port] / path / [:parameters][?query]#fragment
   当proxy_pass 指令后的URL带路径【即是/或/path】和不带路径时,Nginx反向代理传递给后端服务器的请求存在不同。
   客户端的请求:http://192.168.241.137:10180/urltest/test
   Nginx代理服务器IP: 192.168.241.137  端口为10180
   后端Nginx服务器IP:192.168.241.141 端口为18081
   Nginx web服务器的配置

二 实验过程

实验一:代理请求为 http://192.168.241.141:18081和http://192.168.241.141:18081/时

1 代理请求为 http://192.168.241.141:18081
(1) location 有 / 时代理服务器传给后端的请求为  http://192.168.241.141:18081/urltest/test
(2) location 没有 / 时

代理服务器传给后端的请求为 http://192.168.241.18081/urltest/test

2 当代理请求为 http://192.168.241.141:18081/时
(1) location有 /

代理服务器传给后端的请求为:http://192.168.241.141:18081/test

(2) location 没有 /

代理服务器传给后端的请求为:http://192.168.241.141:18081//test

  实验一总结:当proxy_pass请求的url后面没有 / 时, location匹配部分也属于请求部分,都会将整个请求都将加到proxy_pass请求的url部分,即后端接收到的请求为http://192.168.241.141:18081/urltest/test
  当proxy_pass请求的url后面存在/ 时,localtion匹配部分只是用于匹配,不属于请求部分,需要在客户端请求部分将location匹配部分减去:
  location 匹配 /urltest , 则是 http://192.168.241.141:18081/+(/urltest/test - /urltest), 即http://192.168.241.141:18081//test
  location 匹配 /urltest/, 则是 http://192.168.241.141:18081/+(/urltest/test  - /urltest/), 即http://192.168.241.141:18081/test

实验二:当代理请求为 http://192.168.241.141:18081/web和http://192.168.241.141:18081/web/时

  1. 当请求为 http://192.168.241.141:18081/web
    (1) location 有 /后端服务器接收到的请求为: http://192.168.241.141:18081/web +(/urltest/test - /urltest/), 即为: http://192.168.241.141:18081/webtest

    (2) 当location 没有 / 时后端服务器接收到的请求为:http://192.168.241.141:18081/web +(/urltest/test - /urltest), 即为 :http://192.168.241.141:18081/web/test

  2. 当代理请求为 http://192.168.241.141:18081/web/时
    (1) location 有 / 时后端服务器接收到的请求为:http://192.168.241.141:18081/web/ +(/urltest/test - /urltest/), 即为 :http://192.168.241.141:18081/web/test
    (2) location没有 / 时后端服务器接收到的请求为:http://192.168.241.141:18081/web/ +(/urltest/test - /urltest ), 即为 :http://192.168.241.141:18081/web//test

三 结论

  proxy_pass配置中url末尾不存在路径信息时,则直接客户端的请求拼接在proxy_pass中url之后; proxy_pass配置中url末尾存在路径信息时 则将原客户端请求去除location匹配表达式后的内容拼接在proxy_pass中的url之后。


本篇文章来源于微信公众号: 运维小工



微信扫描下方的二维码阅读本文

此作者没有提供个人介绍
最后更新于 2023-06-19