nginx protocol_error ai_generated partial

上游服务器在读取响应头时发送了无效的内容长度:0

upstream sent invalid content-length: 0 while reading response header from upstream

ID: nginx/upstream-sent-invalid-content-length-zero

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
1证据数
2024-05-20首次发现

版本兼容性

版本状态引入弃用备注
nginx 1.24.0 active
nginx 1.22.1 active
nginx 1.20.2 active
nginx 1.18.0 active

根因分析

上游服务器发送了值为 0 的 Content-Length 头部,但包含了响应体,违反了 HTTP/1.1 规范,导致 nginx 拒绝响应。

English

The upstream server sent a Content-Length header with value 0 but included a response body, violating HTTP/1.1 specifications and causing nginx to reject the response.

generic

官方文档

https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_headers

解决方案

  1. Add 'proxy_ignore_headers Content-Length;' in the location block to make nginx ignore the Content-Length header from upstream, allowing the response to be processed based on chunked encoding or connection close.
  2. Fix the upstream application to not send Content-Length: 0 when there is a body; use chunked transfer encoding instead by setting 'Transfer-Encoding: chunked' and omitting Content-Length.
  3. If the upstream is a legacy server that cannot be changed, use a proxy module like 'ngx_http_lua_module' to strip the Content-Length header: 'header_filter_by_lua_block { if ngx.header["Content-Length"] == 0 then ngx.header["Content-Length"] = nil end }'

无效尝试

常见但无效的做法:

  1. 85% 失败

    The error is about header semantic validity, not buffer size.

  2. 90% 失败

    proxy_set_header modifies request headers, not response headers.

  3. 95% 失败

    The error occurs during header parsing, which is independent of response buffering.