Nginx代理WebSocket需手动配置详细日志:在http块定义含$http_upgrade、$http_connection等字段的log_format,在location中启用access_log和debug级error_log,并验证proxy_http_version 1.1、Upgrade与Connection头三项核心配置,辅以curl握手测试和tcpdump抓包排查。

Linux 下 Nginx 代理 WebSocket 时,日志默认不记录 WebSocket 升级过程和连接细节,需手动配置 access_log、error_log 及相关变量才能完整排查。关键在于启用详细日志级别、捕获 HTTP 升级头、记录连接状态,并结合抓包辅助验证。
开启 Nginx WebSocket 代理的详细访问日志
默认 access_log 不体现 WebSocket 特征(如 Upgrade: websocket),需自定义 log_format 包含关键字段:
- 在
http块中添加格式(推荐放在nginx.conf的http段):
log_format websocket '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'upstream_addr:$upstream_addr '
'upstream_status:$upstream_status '
'rt:$request_time uct:$upstream_connect_time '
'uht:$upstream_header_time udt:$upstream_response_time '
'ws_upgrade:"$http_upgrade" ws_connection:"$http_connection"';- 在 server 或 location 块中启用该格式(尤其 WebSocket 所在的
location /ws/等路径):
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
<pre class='brush:php;toolbar:false;'>access_log /var/log/nginx/websocket_access.log websocket;
error_log /var/log/nginx/websocket_error.log debug; # 注意:debug 级别需编译支持}
- 重启 Nginx:
sudo nginx -t && sudo systemctl reload nginx
启用 error_log debug 级别精准定位握手失败
WebSocket 握手失败(如 400、502、连接被重置)常因代理头或后端响应异常,仅靠 access_log 不够,需 error_log 输出协议交互细节:
- 确保 Nginx 编译时启用了
--with-debug(检查:nginx -V 2>&1 | grep -o with-debug) - 将对应 location 的 error_log 设为
debug(如上例),或全局临时设为:error_log /var/log/nginx/error.log debug; - debug 日志会输出:
http proxy header: "HTTP/1.1 101 Switching Protocols"、upstream sent no valid HTTP/1.0 header、client closed connection等关键线索 - 注意:debug 日志量大,排查完及时调回
error或warn级别
验证 WebSocket 代理关键配置是否生效
即使日志开启,若核心代理参数缺失,WebSocket 仍会退化为 HTTP 轮询或直接失败。检查以下三点是否全部存在:
- proxy_http_version 1.1:WebSocket 必须基于 HTTP/1.1,HTTP/1.0 不支持 upgrade
-
proxy_set_header Upgrade $http_upgrade:透传客户端的
Upgrade: websocket头 -
proxy_set_header Connection "upgrade":显式设置 Connection 头为
upgrade(不能写成$http_connection,因浏览器可能发keep-alive, upgrade,需强制覆盖)
可 curl 模拟握手验证 Nginx 是否正确转发头:
curl -i -N \ -H "Connection: Upgrade" \ -H "Upgrade: websocket" \ -H "Sec-WebSocket-Version: 13" \ -H "Sec-WebSocket-Key: $(openssl rand -base64 16)" \ http://your-domain.com/ws/
观察响应中是否含 HTTP/1.1 101 Switching Protocols 及对应头 —— 若返回 200/400/502,则配置或后端有问题。
结合 tcpdump 抓包确认真实连接行为
当日志显示“已升级”但前端仍断连,可能是 TCP 层问题(如防火墙、超时、NAT 中断)。用 tcpdump 直接看三次握手与 FIN/RST:
- 监听 Nginx 入口端口(如 80/443)和上游端口(如 8080):
sudo tcpdump -i any -nn port 80 or port 8080 -w ws_debug.pcap
- 复现问题后,用 Wireshark 打开 pcap,过滤
tcp.stream eq 0查看单个 WebSocket 连接流 - 重点观察:
– 客户端是否发出GET /ws/ ... Upgrade: websocket
– Nginx 是否原样转发到后端
– 后端是否返回101 Switching Protocols
– 连接建立后是否有大量 RST 或空闲超时断开(WebSocket 长连接需防中间设备 kill)
常见干扰:云厂商 SLB、防火墙默认 60 秒空闲超时,需同步调高 proxy_read_timeout 和 proxy_send_timeout(建议 ≥ 300)。


















