Nginx proxy_pass 路径末尾加不加 / 的问题
今天在配置nginx转发的时候遇到了一个问题:proxy_pass路径末尾加不加 / 差别很大。下边两种配置跳转的路径是不一样的。
# nginx配置
server {
listen 8088;
server_name localhost;
location ^~ /test/ {
proxy_pass http://localhost:8000/; # 带 /
}
location ^~ /test/ {
proxy_pass http://localhost:8000; # 不带 /
}
}
在任意目录下运行 puer
(启动一个文件服务器,默认8000端口,nginx上边的配置会代理过来)
# 文件服务器根目录
├── test
│ ├── index.html
├── index.html
├── rewrite
├── ├── index.html
我们在浏览器中输入 http://localhost/test/index.html
- 带/实际访问的是
http://localhost:8000/index.html
(相当于根或绝对路径,不会在代理路径后拼接locaiton中匹配规则的路径,比如上边的test
) - 无/实际访问的是
http://localhost:8000/test/index.html
(相当于相对路径,会在代理路径后拼接locaiton中匹配规则的路径)
当然,我们可以使用 rewrite
来实现 proxy_pass后加 / 的效果
# 实际访问的是 `http://localhost:8000/index.html`
location ^~ /test/ {
rewrite /test/(.+)$ /$1 last;
}
同样我们也可以改为如下:
# 实际访问的是 `http://localhost:8000/rewrite/index.html`
location ^~ /test/ {
rewrite /test/(.+)$ /rewrite/$1 last;
}
rewrite 和 proxy_pass执行顺序
- 执行server下的rewrite
- 执行location匹配
- 执行location下的rewrite
rewrite 和 proxy_pass 跳转域名区别
- rewrite 同一域名跳转
- proxy_pass 任意域名跳转
参考资料:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报