nginx

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > nginx > nginx proxy_pass 路径拼接

nginx proxy_pass 路径拼接的具体实现

作者:冰糖拌面

本文主要介绍了nginx proxy_pass 路径拼接的具体实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

主要是记录proxy_pass在做转发时,转发的url生成规则,本文以通用字符串匹配为例,就是类似如下

location /aaa {
    proxy_pass ...
}

正则及精准匹配放到下篇说

正文

对于访问后端路径的拼接,proxy_pass可以分为两种,一种是携带URI(或者说是某个uri的一部分),一种是不带uri(或者说仅有协议 + host)

例如 http://localhost:80 就是不带uri的地址

例如 http://localhost:80/ 和 http://localhost:80/aaa 就是携带URI的地址

以下案例全部是假设 nginx设置server 为example.com,即

http {
    server {
        listen 8080;
        server_name example.com; 
    }
}

不带uri

这种比较好说,访问nginx的URI直接拼接到proxy_pass的后面就可以了,举例如下

location /aaa {
    proxy_pass http://localhost
}
location /aaa/ {
    proxy_pass http://localhost
}

1、对于上面两种写法,访问nginx的URL为 http://example.com:8080/aaa/xxx,nginx转发的地址将是 http://localhost/aaa/xxx

2、但是对于http://example.com:8080/aaa就会有所不同,如果只有location /aaa/ , 那么http://example.com:8080/aaa会被重定向为http://example.com:8080/aaa/

带uri

这种就是,将原URL的URI匹配到的location后面的内容去掉,再拼接到proxy_pass后,常见案例如下

第一种

location /aaa {
    proxy_pass http://localhost/
}

访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost//xxx 

解析就是 /aaa/xxx 去掉 /aaa 剩下了 /xxx,拼接到http://localhost/ 后面 成了 http://localhost//xxx

这种写法不对,多了一个/,但是我用来测试的nginx1.25.1没有问题,依然转发到正确的 http://localhost/xxx,但是不建议搞这种特立独行的

第二种

location /aaa/ {
    proxy_pass http://localhost/
}

 访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost/xxx 

解析就是 /aaa/xxx 去掉 /aaa/ 剩下了 xxx,拼接到http://localhost/ 后面 成了 http://localhost/xxx

第三种

location /aaa/ {
    proxy_pass http://localhost/ccc
}

 访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost/cccxxx

解析就是 /aaa/xxx 去掉 /aaa/ 剩下了 xxx,拼接到http://localhost/ccc 后面 成了 http://localhost/cccxxx

这一眼看过去就是个错误

第四种

location /aaa {
    proxy_pass http://localhost/ccc
}

 访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost/ccc/xxx

解析就是 /aaa/xxx 去掉 /aaa 剩下了 /xxx,拼接到http://localhost/ccc 后面 成了 http://localhost/ccc/xxx

第五种

location /aaa/ {
    proxy_pass http://localhost/ccc/
}

 访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost/ccc/xxx

解析就是 /aaa/xxx 去掉 /aaa/ 剩下了 xxx,拼接到http://localhost/ccc/ 后面 成了 http://localhost/ccc/xxx 

第六种

location /aaa {
    proxy_pass http://localhost/ccc/
}

 访问 http://example.com:8080/aaa/xxx ,nginx将转发到 http://localhost/ccc//xxx

解析就是 /aaa/xxx 去掉 /aaa 剩下了 /xxx,拼接到http://localhost/ccc/ 后面 成了 http://localhost/ccc//xxx 

这种也是非正常的拼接,但是大多数浏览器、中间件都能支持,不建议这么做

总结

1、proxy_pass后面不带uri的话,原URL的URI直接拼接proxy_pass就得出访问的后端地址

2、对于带uri的proxy_pass,将原URL的URI匹配到的location后面的内容去掉,再拼接到proxy_pass后

3、建议location 和 proxy_pass的结尾要么都带 / ,要么都不带/,否则会出现案例1、3、6的情况

到此这篇关于nginx proxy_pass 路径拼接的具体实现的文章就介绍到这了,更多相关nginx proxy_pass 路径拼接内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文