V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
kugouo4
V2EX  ›  NGINX

小白请教一下 nginx 的 location 和 proxy_pass 后面有无斜杠的区别

  •  1
     
  •   kugouo4 · 2020-03-06 11:46:05 +08:00 · 3667 次点击
    这是一个创建于 1509 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我结合 tomcat 和 nginx 也做了一些测试,具体如下,

    例如访问地址是 http://nginx/test/a.html

    配置 1:
    
    location /test {
    
    ...
    
      proxy_pass http://host:9020;
    
    }
    
    结果:
    
    test/a.html
    
    配置 2:
    
    location /test {
    
    ...
    
      proxy_pass http://host:9020/;
    
    }
    
    结果:
    
    ROOT/a.html
    
    配置 3:
    
    location /test/ {
    
    ...
    
      proxy_pass http://host:9020;
    
    }
    
    结果:
    
    test/a.html
    
    配置 4:
    
    location /test/ {
    
    ...
    
      proxy_pass http://host:9020/;
    
    }
    
    结果:
    
    ROOT/a.html
    
    配置 5:
    
    location /test/ {
    
    ...
    
      proxy_pass http://host:9020/testapp;
    
    }
    
    结果:
    
    ROOT/testappa.html
    
    配置 6:
    
    location /test/ {
    
    ...
    
      proxy_pass http://host:9020/testapp/;
    
    }
    
    结果:
    
    testapp/a.html
    
    
    
    配置 7:
    
    location /test {
    
    ...
    
      proxy_pass http://host:9020/testapp;
    
    }
    
    结果:
    
    testapp/a.html
    
    配置 8:
    
    location /test {
    
    ...
    
      proxy_pass http://host:9020/testapp/;
    
    }
    
    结果:
    
    testapp/a.html
    
    
    

    疑问就是配置 7 和 8 结果是一样的?

    为什么配置 7 的结果不依照类似配置 1 的结果?

    不是 testapp/test/a.html 而是 testapp/a.html ?

    4 条回复    2020-03-06 13:58:15 +08:00
    37Y37
        1
    37Y37  
       2020-03-06 12:35:00 +08:00
    那是因为。。你 7 的测试有问题。。标准的处理应该是

    1. 目标地址中不带 uri ( proxy_pass http://tomcats )。此时新的目标 url 中,匹配的 uri 部分不做修改,原来是什么就是什么

    2. 目标地址中带 uri ( proxy_pass http://tomcats/,/也是 uri ),此时新的目标 url 中,匹配的 uri 部分将会被修改为该参数中的 uri

    参考这个 https://ops-coffee.cn/s/jyunn_otq2ntxch0mtcjug,多测试几遍看看
    ddsfeng
        2
    ddsfeng  
       2020-03-06 13:02:07 +08:00   ❤️ 1
    @kugouo4 参考这个 github.com/xqin/nginx-proxypass-server-paths

    之前也有过这个困惑, 然后无意间 看到有人做了个总结, 然后用 docker 实践了一下, 记录一下结果.
    kugouo4
        3
    kugouo4  
    OP
       2020-03-06 13:15:52 +08:00
    @37Y37
    @ddsfeng
    谢谢二位,看过两位回复和链接后总算弄清楚了
    Aresxue
        4
    Aresxue  
       2020-03-06 13:58:15 +08:00
    在 nginx 中配置 proxy_pass 时,当在后面的 url 加上了 /,相当于是绝对根路径,则 nginx 不会把 location 中匹配的路径部分代理走;如果没有 /,则会把匹配的路径部分也给代理走
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3297 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:48 · PVG 21:48 · LAX 06:48 · JFK 09:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.