Nginx的location路径与proxy_pass匹配规则说明

 更新时间:2024年06月19日 08:48:30   作者:kse_music  

这篇文章主要介绍了Nginx的location路径与proxy_pass匹配规则说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

目录
  • 路径替换
  • 总结
    • 当访问地址是 http://127.0.0.1/api/user/list
    • 注意
  • 最后

    路径替换

    配置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/;
    }

    最后

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持小闻网。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。