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

2020-03-06 11:46:05 +08:00
 kugouo4

我结合 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 ?

3675 次点击
所在节点    NGINX
4 条回复
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
2020-03-06 13:02:07 +08:00
@kugouo4 参考这个 github.com/xqin/nginx-proxypass-server-paths

之前也有过这个困惑, 然后无意间 看到有人做了个总结, 然后用 docker 实践了一下, 记录一下结果.
kugouo4
2020-03-06 13:15:52 +08:00
@37Y37
@ddsfeng
谢谢二位,看过两位回复和链接后总算弄清楚了
Aresxue
2020-03-06 13:58:15 +08:00
在 nginx 中配置 proxy_pass 时,当在后面的 url 加上了 /,相当于是绝对根路径,则 nginx 不会把 location 中匹配的路径部分代理走;如果没有 /,则会把匹配的路径部分也给代理走

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/650344

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX