当前位置: 首页 > ds >正文

nginx 配置要领

你提出的问题非常好!确实在配置 WebSocket 代理时,proxy_pass 的 URL 处理需要特别注意。以下是关键解释和修正建议:


1. 原配置的问题分析

location /ws/ {proxy_pass http://fastapi-container:8000;  # 会保留 /ws/ 前缀传递给后端
}
  • 这种配置会将完整路径(包括 /ws/)传递给 FastAPI 服务。
  • 如果你的 FastAPI 的 WebSocket 路由是 /ws/chat,实际请求会被转发为:
    http://fastapi-container:8000/ws/chat

2. 两种正确的配置方式

方式 1:保留路径前缀(推荐)
location /ws/ {proxy_pass http://fastapi-container:8000;  # 不写结尾的 /proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";
}
  • 行为
    • 请求 wss://your-domain.com/ws/chat
    • → 转发到 http://fastapi-container:8000/ws/chat
  • 适用场景
    FastAPI 的 WebSocket 路由需要完整路径(如 @app.websocket("/ws/chat")
方式 2:去除路径前缀
location /ws/ {proxy_pass http://fastapi-container:8000/;  # 结尾有 /proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";
}
  • 行为
    • 请求 wss://your-domain.com/ws/chat
    • → 转发到 http://fastapi-container:8000/chat(去除了 /ws 前缀)
  • 适用场景
    FastAPI 的 WebSocket 路由直接使用根路径(如 @app.websocket("/chat")

3. 完整修正方案

情况 1:FastAPI 需要完整路径
location /ws/ {proxy_pass http://fastapi-container:8000;  # 无结尾 /# 其他 WebSocket 头保持不变...
}# FastAPI 代码
@app.websocket("/ws/chat")  # 匹配完整路径
async def websocket_endpoint(websocket: WebSocket):...
情况 2:FastAPI 不需要前缀
location /ws/ {proxy_pass http://fastapi-container:8000/;  # 有结尾 /# 其他 WebSocket 头保持不变...
}# FastAPI 代码
@app.websocket("/chat")  # 路径已去除 /ws
async def websocket_endpoint(websocket: WebSocket):...

4. 测试验证方法

  1. 检查实际转发路径
    在 FastAPI 中添加日志:

    @app.websocket("/ws/chat")
    async def websocket_endpoint(websocket: WebSocket):print("Received WebSocket at:", websocket.url.path)  # 查看实际路径
    
  2. Nginx 调试日志
    在 Nginx 配置中添加:

    error_log /var/log/nginx/error.log debug;
    

5. 常见误区

错误配置结果修正
proxy_pass http://backend; + location /ws/保留 /ws/ 前缀符合预期
proxy_pass http://backend/; + location /ws/去除 /ws/ 前缀需调整 FastAPI 路由
proxy_pass http://backend/ws/; + location /ws/重复 /ws/ws/绝对避免

总结

  • 关键规则
    • proxy_pass 的 URL / 结尾 → 去除 location 匹配的前缀
    • proxy_pass 的 URL / 结尾 → 保留完整路径
  • 推荐做法
    保持 Nginx 的 location 和 FastAPI 路由路径一致,避免混淆。
http://www.xdnf.cn/news/3440.html

相关文章:

  • 客户服务升级:智能语音外呼系统在多领域的场景应用解析
  • 大模型时代的新燃料:大规模拟真多风格语音合成数据集
  • 面经很简单的
  • 机器学习_KNN算法
  • 【SpringBoot】基于mybatisPlus的博客管理系统(2)
  • 汽车电子 专栏文章汇总
  • python+echart绘制一个听力图
  • 常用电机类型及其特点对比
  • 如何用fiddler进行弱网测试(工作常用篇)
  • sd webui 安装插件sd-webui-EasyPhoto依赖安装失败解决办法
  • 基于深度强化学习训练一个会走迷宫的ai
  • java之Integer、Double自动拆装箱比较,踩坑值int和Integer比较之空指针异常
  • WPF之TextBox控件详解
  • 第八节:目录操作
  • 二叉树的路径总和问题(递归遍历,回溯算法)
  • 如何理解神经网络训练的循环过程
  • 产品月报|睿本云4月产品功能迭代
  • MS31860T——8 通道串行接口低边驱动器
  • 制造业行业ERP软件部署全流程指南:从选型到维护,怎么做?
  • 多线程爬虫中实现线程安全的MySQL连接池
  • Java程序员如何设计一个高并发系统?
  • 基于MCP协议实现一个智能审核流程
  • 虚拟内存笔记(一)
  • AVPro Video加载视频文件并播放,可指定视频文件的位置、路径等参数
  • 运用ESS(弹性伸缩)技术实现服务能力的纵向扩展
  • foxmail时不时发送不了邮件问题定位解决过程
  • 苍穹外卖11
  • Windows查看和修改IP,IP互相ping通
  • 使用模块中的`XPath`语法提取非结构化数据
  • Learning vtkjs之ImageMarchingCubes