Nginx 反代升级
proxy_http_version 1.1、Upgrade 头。
25 分钟
Nginx 反代升级
WebSocket 握手是 HTTP,经 Nginx 反代时必须 HTTP/1.1 + Upgrade + Connection。CodeRoadMap 的 prod.conf.example 与 ngx-proxy 已含 HMR/WS 模板。
学习目标
- 配置
/ws到 Spring Boot 的 upgrade 头 - 设置读超时避免长连接被误杀
- 区分 platform 与 backend 的 WS 路径
最小配置
location /ws/ {
proxy_pass http://coderoadmap_backend/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 3600s;
}
map 块(通常在 nginx.conf):
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
缺 Upgrade 时握手失败,浏览器报 Unexpected response code: 200。
与 REST 共用 upstream
location /api/ {
proxy_pass http://coderoadmap_backend/;
# 普通 HTTP,无需 Upgrade
}
location /ws/ {
proxy_pass http://coderoadmap_backend/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
/api 走 REST;/ws 走 WebSocket(ws-stomp 端点 /ws)。
超时与扩展
| 指令 | 建议 | 原因 |
|---|---|---|
proxy_read_timeout | 3600s+ | 长连接空闲不被断 |
proxy_send_timeout | 3600s | 大消息广播 |
ip_hash | 多实例时 | 见 ws-scale |
Next.js dev HMR 的 / location 同样需要 Upgrade,勿与 /ws 混配错误 upstream。
练习
- 对比
test.conf.example与prod.conf.example的 WS 相关行