Nginx 报错 upstream sent invalid chunked response 排障与传输调优
Nginx 反向代理向客户端返回 502 Bad Gateway 并在错误日志记录 upstream sent invalid chunked response。本文深入剖析上游分块编码缺陷、gzip 压缩冲突与 proxy_http_version 调优实战。
在微服务架构中使用 Nginx 作为接入反向代理时,前端或移动端在调用某接口获取较大流式数据、导出数据或拉取大型 JSON 时,连接突然中断并返回 502 Bad Gateway。查看 /var/log/nginx/error.log,出现大面积警告记录:[error] 1234#1234: *567 upstream sent invalid chunked response while reading upstream, client: 192.168.1.50, server: api.example.com, request: "GET /api/stream-data HTTP/1.1", upstream: "http://10.244.2.15:8080/api/stream-data"。
故障现象与日志
查看 Nginx 错误日志:
2026/01/01 10:00:00 [error] 1234#1234: *789 upstream sent invalid chunked response while reading upstream, client: 10.0.0.1, server: api.example.com, request: "GET /export/records HTTP/1.1", upstream: "http://192.168.2.15:8080/export/records", host: "api.example.com"
客户端在接收数据流接收到一半时被异常掐断,终端提示传输损坏。
根本原因剖析
- Nginx 默认向上游使用 HTTP/1.0 发送请求(核心历史背景):
在 Nginx 的反向代理模块中,
proxy_http_version默认值是1.0(而非 1.1)。 而在 HTTP/1.0 协议规范中,根本没有定义Transfer-Encoding: chunked分块传输机制。当现代后端框架(如 Node.js、Go gin、Spring WebFlux)在返回流式数据时,强行采用了 chunked 分块,或者在开启 gzip 压缩时产生编码混乱,Nginx 认为上游协议违背了 HTTP/1.0 握手约定,判定其为非法的 chunked 响应并抛出 502。 - 后端服务在发送 chunked 数据流中途意外崩溃退出:后端服务处理到第 5000 条记录时抛出了未捕获的运行时异常(如 OutOfMemory 或空指针),直接提前关闭了 TCP Socket,**未能向下游发送合法的 0 字节结束块(`0
`)**。Nginx 读取到 EOF 却未收到合法的结束标记,认定响应体损坏。 3. 双重 Gzip 压缩冲突:后端应用服务开启了 Gzip 压缩,而 Nginx 反代层同样对 upstream 开启了二次压缩,导致分块长度计算失真。
诊断排查步骤
- 直接绕过 Nginx 请求后端真实服务验证响应格式:
curl -v -N http://192.168.2.15:8080/export/records > /dev/null
观察数据流是否能完整平稳输出,还是在中间某一秒突然中断报 transfer closed with outstanding read data remaining。
- 检查当前 Nginx location 块的反代配置:
查看是否遗漏了
proxy_http_version 1.1指令。
解决方案与参数配置
步骤一:强制 Nginx 与上游采用 HTTP/1.1 协议(标准最佳实践)
在 nginx.conf 的代理配置中,显式将向上游请求的协议升级为 HTTP/1.1,并清空 Connection 头以支持长连接与标准分块:
location /api/ {
proxy_pass http://backend_pool;
# 关键设置:强制向上游使用 HTTP/1.1 协议
proxy_http_version 1.1;
proxy_set_header Connection "";
# 保持客户端 Host 与 IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 对于流式分块传输,建议关闭代理缓冲,实现实时转发
proxy_buffering off;
# 调大读写超时时间,防止慢流被掐断
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
步骤二:避免双重 Gzip 压缩冲突
如果后端服务已经自身压缩了数据(返回了 Content-Encoding: gzip),指示 Nginx 不要重复解压或压缩:
在 location 块中设置:
# 告诉上游 Nginx 支持直接透传 gzip,不要产生二次分块压缩
proxy_set_header Accept-Encoding gzip;
步骤三:测试语法并平滑重载生效
nginx -t && nginx -s reload
重载后,再次调用大文件或数据流接口,数据传输顺畅连续,invalid chunked response 告警彻底消失。


