码迷,mamicode.com
首页 > 其他好文 > 详细

nginx反向代理配置里的location 反斜杠用法

时间:2019-07-03 13:34:32      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:order   不同的   例子   测试方法   不用   反向代理   too   location   proxy   

两台nginx服务器

nginx A: 192.168.1.48

nginx B: 192.168.1.56

一. 测试方法

在nginx A中配置不同的规则,然后请求nginx A: http://192.168.1.48/foo/api

观察nginx B收到的请求,具体操作是查看:‘http://‘.$_SERVER[‘HTTP_HOST‘].$_SERVER[‘PHP_SELF‘].‘?‘.$_SERVER[‘QUERY_STRING‘];

二. 测试过程及结果

案例1

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/;
} 

 

nginx B收到的请求:/api

案例2

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/;
} 

 

nginx B收到的请求://api

案例3

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56;
} 

 

nginx B收到的请求:/foo/api

案例4

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56;
} 

 

 

nginx B收到的请求:/foo/api

案例5

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/bar/;
} 

 

nginx B收到的请求:/bar/api

案例6

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/bar/;
} 

 

nginx B收到的请求:/bar//api

案例7

nginx A配置:

 

location /foo/ {
  proxy_pass http://192.168.1.56/bar;
} 

 

nginx B收到的请求:/barapi

案例8

nginx A配置:

 

location /foo {
  proxy_pass http://192.168.1.56/bar;
} 

 

nginx B收到的请求:/bar/api

看到这里是不是都晕了呢,其实是有规律的

现在把这些案例按表格排列起来,结果表示nginx B收到的请求

表一

 
案例locationproxy_pass结果
1 /foo/ http://192.168.1.48/ /api
2 /foo http://192.168.1.48/ //api
3 /foo/ http://192.168.1.48 /foo/api
4 /foo http://192.168.1.48 /foo/api

 

 

 

 

 

 

 

表二

 
案例locationproxy_pass结果
5 /foo/ http://192.168.1.48/bar/ /bar/api
6 /foo http://192.168.1.48/bar/ /bar//api
7 /foo/ http://192.168.1.48/bar /barapi
8 /foo http://192.168.1.48/bar /bar/api

 

 

 

 

 

 

 

. 解析

原请求路径:本文中统一为 "/foo/api"

location: 上面表格中的location列

proxy_pass:上面表格中的proxy_pass列

新请求路径:nginx将原请求路径处理过后的字符串

重点对 proxy_pass 进行分析,可以分为3种形式

然后按照ip:port后是否接了字符串归为2类,"/"也是字符串,因此1归为一类,2、3归为一类,下面对这两类情况进行说明

当 proxy_pass 的 ip:port 后未接字符串的时候,nginx 会将原请求路径原封不动地转交给下一站 nginx,如案例3和4

当 proxy_pass 的 ip:port 后接了字符串的时候,nginx 会将 location 从 原请求路径 中剔除,再将剩余的字符串拼接到 proxy_pass 后生成 新请求路径,然后将 新请求路径 转交给下一站nginx(上面一种情况实际上和这个是一样的,只不过剔除的字符串是空串~~)

举个最让人疑惑的例子:案例7。proxy_pass 的 ip:port 后接了字符串 "/bar",因此将 location:"/foo/" 从 原请求路径:"/foo/api" 中剔除,变为"api",再将"api"拼接到proxy_pass: http://192.168.1.48/bar 后生成了新请求url:" http://192.168.1.48/barapi ",因此下一站的nginx收到的请求就是 "/barapi"。

案例6:proxy_pass 的 ip:port 后接了字符串 "/bar/",因此将 location:"/foo" 从 原请求路径 "/foo/api" 中剔除,变为 "/api",再将 "/api" 拼接到proxy_pass: http://192.168.1.48/bar/ 后生成了 新请求路径:" http://192.168.1.48/bar//api ",因此下一站的nginx收到的请求就是 /bar//api。

其它的案例都可以以此类推,现在终于搞明白了,再也不用一头雾水。

转载 https://www.jb51.net/article/146975.htm,仅供自己学习

nginx反向代理配置里的location 反斜杠用法

标签:order   不同的   例子   测试方法   不用   反向代理   too   location   proxy   

原文地址:https://www.cnblogs.com/hualingyun/p/11125649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!