# 上游发送了无效的 Content-Length：0 但主体非空，从上游读取响应头时，客户端：10.0.0.1，服务器：example.com

- **ID:** `nginx/upstream-sent-invalid-content-length-zero-body`
- **领域:** nginx
- **类别:** protocol_error
- **验证级别:** ai_generated
- **修复率:** 74%

## 根因

上游发送了 Content-Length 为 0 但随后包含了非空的响应主体，导致 nginx 检测到不匹配并终止。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| nginx 1.18.0 | active | — | — |
| nginx 1.20.1 | active | — | — |
| nginx 1.22.0 | active | — | — |
| nginx 1.24.0 | active | — | — |

## 解决方案

1. ```
   Fix the upstream application to correctly set Content-Length to the actual body size. For example, in a Go HTTP handler, ensure Content-Length matches the body:
func handler(w http.ResponseWriter, r *http.Request) {
    body := []byte("Hello")
    w.Header().Set("Content-Length", strconv.Itoa(len(body)))
    w.Write(body)
}
Avoid hardcoding Content-Length to 0 when writing a body.
   ```
2. ```
   Use nginx's proxy_hide_header Content-Length; to remove the upstream's Content-Length header, forcing nginx to use chunked encoding or calculate length from the actual body. Example:
location / {
    proxy_pass http://upstream;
    proxy_hide_header Content-Length;
}
   ```

## 无效尝试

- **Set proxy_request_buffering off;** — Request buffering affects client request body, not response body handling from upstream. (95% 失败率)
- **Increase proxy_buffer_size** — Buffer size does not affect the Content-Length validation logic; the error is about header-body mismatch. (93% 失败率)
- **Disable chunked transfer encoding with proxy_set_header Transfer-Encoding '';** — This modifies request headers to upstream, not the response; the error is in the response. (88% 失败率)
