location路径与proxy_pass匹配规则
- 路径替换
- 总结
- 当访问地址是 http://127.0.0.1/api/user/list
- 注意:location后斜杆与proxy_pass后斜杆"/"问题,最好要么两者都加斜杆,要么都不加
路径替换
- 配置proxy_pass时,可以实现URL路径的部分替换。
- proxy_pass的目标地址,默认不带/,表示只代理域名(ip+端口),path和query部分不会变(把请求的path和query拼接到proxy_pass目标域名之后作为代理的URL)
- 如果在目标地址端口后有‘/’或者‘/xx/yy’等目录,则表示把path中location匹配成功的部分剪切掉之后再拼接到proxy_pass目标地址后面
比如请求 /a/b.html
location /a {proxy_pass http://server;
}
实际代理的目标url是http://server/a/b.html (把/a/b.html拼接到http://server之后)
location /a/ {proxy_pass http://server/;
}
总结
当访问地址是 http://127.0.0.1/api/user/list
- 若proxy_pass代理地址端口后无任何字符,则转发后地址为:代理地址+访问的path
location | proxy_pass | 代理路径 |
---|---|---|
/api/ | http://server:8080 | http://server:8080/api/user/list |
/api/ | http://server:8080/ | http://server:8080/user/list |
/api | http://server:8080 | http://server:8080/api/user/list |
/api | http://server:8080/ | http://server:8080/user/list |
- 若proxy_pass代理地址端口后有目录(包括"/"),则转发后地址为:代理地址+访问的path去除location匹配的路径
location | proxy_pass | 代理路径 |
---|---|---|
/api/ | http://server:8080/gw | http://server:8080/gwuser/list |
/api/ | http://server:8080/gw/ | http://server:8080/gw/user/list |
/api | http://server:8080/gw | http://server:8080/gw/user/list |
/api | http://server:8080/gw/ | http://server:8080/gw/user/list |
注意:location后斜杆与proxy_pass后斜杆"/"问题,最好要么两者都加斜杆,要么都不加
以服务地址http://127.0.0.1:5053/api/test/list进行说明,访问地址是http://127.0.0.1/api/test/list。location后斜杆与proxy_pass后斜杆问题如下:
- location、proxy_pass都不加斜杠,实际代理地址:http://127.0.0.1:5053/api/test/list
location /api {proxy_pass http://127.0.0.1:5053;
}
- location加斜杠,proxy_pass不加斜杠,实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api/ {proxy_pass http://127.0.0.1:5053;
}
- location不加斜杠,proxy_pass加斜杠,实际代理地址:http://127.0.0.1:5053//test/list,错误的,也出现了双斜杠
location /api {proxy_pass http://127.0.0.1:5053/;
}
- location、proxy_pass都加斜杠,实际代理地址:http://127.0.0.1:5053/test/list,错误的
location /api/ {proxy_pass http://127.0.0.1:5053/;
}
- location不加斜杠,proxy_pass加"api",实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api {proxy_pass http://127.0.0.1:5053/api;
}
- location加斜杠,proxy_pass加"api",实际代理地址:http://127.0.0.1:5053/apitest/list,错误的,少了一个斜杆
location /api/ {proxy_pass http://127.0.0.1:5053/api;
}
- location不加斜杠,proxy_pass加"api/",实际代理地址:http://127.0.0.1:5053/api//test/list,出现双斜杠问题,后端在认证请求时会校
验失败
location /api {proxy_pass http://127.0.0.1:5053/api/;
}
- location加斜杠,proxy_pass加"api/",实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api/ {proxy_pass http://127.0.0.1:5053/api/;
}