美文网首页Nginx
Nginx 反向代理中 / 符号的一些坑

Nginx 反向代理中 / 符号的一些坑

作者: 舌尖上的大胖 | 来源:发表于2018-12-09 07:57 被阅读0次

    背景

    使用 Nginx 作为反向代理访问一个服务,是很常见的应用场景,但是在配置时,/ 符号使用不当,会导致会映射到原本服务器时,与预期要访问的目标不一致。

    比如:

        location /nginx_location/ {
            proxy_pass http://server/;
        }
    

    其中,locationproxy_pass 的内容,最后的 / 符号是容易被忽略的细节。按照上面的配置,其实在我们心中,期待的结果能符合这样的规律:

    访问的结果,是 Nginx 将 location 中匹配的部分,替换成 proxy_pass 中指定的内容。

    但实际上,大部分情况还是符合这个预期的,也有个别情况引起混乱
    假设:

    • 通过 Nginx 访问的 URL:http://nginx/nginx_location/some/path
    • 期待的访问目标:http://server/some/path

    但实际的结果,与 / 的使用,以及映射目标为根路径或者其它位置都会导致一些差异。

    测试结果

    先说测试结果:

    通过 Nginx Server 访问 http://nginx/nginx_location/some/path

    proxy_pass直接映射到主机,没有其他路径
    location proxy_pass 实际访问目标 关注
    /nginx_location/ http://server http://server/nginx_location/some/path
    /nginx_location/ http://server/ http://server/some/path
    /nginx_location http://server http://server/nginx_location/some/path
    /nginx_location http://server/ http://server//some/path
    proxy_pass直接映射到主机的 /test
    location proxy_pass 实际访问目标 关注
    /nginx_location/ http://server/test http://server/testsome/path
    /nginx_location/ http://server/test/ http://server/test/some/path
    /nginx_location http://server/test http://server/test/some/path
    /nginx_location http://server/test/ http://server/test//some/path

    这些是对于 locationproxy_pass 分别是否带有 / 的测试结果。可以总结如下:

    • 引发关注问题的,都是 locationproxy_pass 不带 / 的,所以最好都带上
    • 对于映射目标直接是主机,不带任何路径的,也不带 /, 会将 /nginx_location/ 自动拼接

    通过 Nginx Server 访问 http://nginx/nginx_locationxxx/some/path

    测试过程中,发现对于 location 不带 / 的情况,在一些特殊场景也有一些有意思的效果,整理出来以便发现规律,但还是建议正常情况不要这么使用。

    proxy_pass直接映射到主机,没有其他路径
    location proxy_pass 实际访问目标 关注
    /nginx_location http://server http://server/nginx_locationxxx/some/path
    /nginx_location http://server/ http://server/xxx/some/path
    proxy_pass直接映射到主机的 /test
    location proxy_pass 实际访问目标 关注
    /nginx_location http://server/test http://server/testxxx/some/path
    /nginx_location http://server/test/ http://server/test/xxx/some/path

    测试环境:1.15.7

    (完)

    相关文章

      网友评论

        本文标题:Nginx 反向代理中 / 符号的一些坑

        本文链接:https://www.haomeiwen.com/subject/jjlhhqtx.html