nginx proxy_pass中斜杠问题

一、location不带前缀匹配

c 复制代码
# 不带/
location / {
	proxy_pass http://192.168.1.11;
}

# 带/
location / {
	proxy_pass http://192.168.1.11/;
}

1.不带子路径

在浏览器访问

shell 复制代码
http://x.x.x.x

在日志中的显示区别。可以看出 多了一个/

shell 复制代码
"GET /"
"GET //"

返回结果是一样的

2.带子路径

在浏览器访问

shell 复制代码
http://x.x.x.x/server

在日志中的两种location 的结果是一样的

shell 复制代码
GET /server/
GET /server/

3.总结:

location和proxy_pass都是默认配置,带不带/ 访问效果都一样

二、location带前缀匹配

1.proxy_pass 不带/

c++ 复制代码
location /server {
		proxy_pass http://192.168.1.11;
}

# 浏览器访问
http://x.x.x.x/server/a
# 日志显示结果如下
GET /server/a/
    
# 也就是说nginx会把location中的url以及子路径拼接给proxy_pass 的后端地址

2.proxy_pass 带/

c++ 复制代码
location /server {
		proxy_pass http://192.168.1.11/;
}

# 浏览器访问
http://x.x.x.x/server/a

# 日志显示结果如下
GET //a/

这里可以看出,proxy_pass 带上/以后,再转发时候不会带上 location中的url(这里指的server这个url),但是后续的子路径(这里指的是/a)会拼接到porxy_pass的路径上

三、proxy_poass带后缀

有时候后端使用的tomcat,tomcat中有很多接口,也就是用很多目录区分的,这时候在转发的时候就就需要带上目录名称了。

1.location无前缀 proxy有后缀

如果是以下配置

shell 复制代码
location / {
        proxy_pass http://192.168.1.11/server;
}

访问

shell 复制代码
http://x.x.x.x/test/data

在后端日志中显示,发现test和server之间没有/隔开。所有就404了

shell 复制代码
GET /servertest/data

所以配置需要加上/,如下

c 复制代码
location / {
        proxy_pass http://192.168.1.11/server/;
}

这样结果就正确了,在后端日志中显示正常了

c 复制代码
GET /server/test/data

2.总结

proxy_pass 最后的/ 有两个作用

2.1 去掉location中的url,不做拼接,但是会拼接后续的子路径。

2.2 在路径拼接的时候,会加上一个/

相关推荐
RisunJan2 小时前
Linux命令-scriptreplay(终端会话回放)
linux·运维·chrome
x²+(y-√³x²)²=13 小时前
Linux打包文件到Windows,文件/文件类型丢失
linux·运维·windows
世人万千丶3 小时前
去重插入与超限淘汰:ArkTS 实现鸿蒙搜索历史的 LIMIT 艺术
运维·服务器·学习·华为·harmonyos·鸿蒙
未来之窗软件服务4 小时前
企业自动化运营-电子合同预览-东方仙盟
运维·自动化·仙盟创梦ide·东方仙盟
Android系统攻城狮4 小时前
Linux PipeWire深度解析之pw_properties_iterate调用流程与实战(六十五)
linux·运维·服务器·音频进阶·pipewire音频进阶
研华科技Advantech5 小时前
案例 | 从离线巡检到在线看护:研华PHM解决方案赋能石油钻井平台智能运维
运维·人工智能·边缘计算
難釋懷5 小时前
Nginx主动健康检查
运维·nginx
ITyunwei09875 小时前
内存溢出报错,实战处理记录
运维·服务器·企业微信
Elastic 中国社区官方博客5 小时前
你的 AI agent 不需要你的 API 密钥:使用 OAuth 2.1 对 Elasticsearch MCP 服务器进行身份验证
大数据·运维·人工智能·elasticsearch·搜索引擎·全文检索
FreeTinker5 小时前
AP AC组网中的远程运维挑战及内网穿透技术应用分析
运维