nginx protocol_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
nginx/1.24.0 active
nginx/1.22.1 active
nginx/1.26.0 active

Root Cause

Upstream server returned a Content-Length header with a negative or non-numeric value, violating HTTP protocol.

generic

中文

上游服务器返回了包含负数或非数字值的 Content-Length 头,违反了 HTTP 协议。

Official Documentation

https://nginx.org/en/docs/http/ngx_http_upstream_module.html

Workarounds

  1. 95% success Fix the upstream application to return a valid Content-Length header (e.g., in Python Flask: remove or set correct Content-Length via response.headers['Content-Length'] = str(len(data)))
    Fix the upstream application to return a valid Content-Length header (e.g., in Python Flask: remove or set correct Content-Length via response.headers['Content-Length'] = str(len(data)))
  2. 80% success Add proxy_ignore_headers Content-Length; in nginx config to ignore upstream's Content-Length if it is invalid (use with caution). Example: location / { proxy_pass http://backend; proxy_ignore_headers Content-Length; }
    Add proxy_ignore_headers Content-Length; in nginx config to ignore upstream's Content-Length if it is invalid (use with caution). Example: location / { proxy_pass http://backend; proxy_ignore_headers Content-Length; }
  3. 85% success Update upstream server code to not send Content-Length for chunked responses (e.g., in Node.js: res.removeHeader('Content-Length') before piping).
    Update upstream server code to not send Content-Length for chunked responses (e.g., in Node.js: res.removeHeader('Content-Length') before piping).

中文步骤

  1. Fix the upstream application to return a valid Content-Length header (e.g., in Python Flask: remove or set correct Content-Length via response.headers['Content-Length'] = str(len(data)))
  2. Add proxy_ignore_headers Content-Length; in nginx config to ignore upstream's Content-Length if it is invalid (use with caution). Example: location / { proxy_pass http://backend; proxy_ignore_headers Content-Length; }
  3. Update upstream server code to not send Content-Length for chunked responses (e.g., in Node.js: res.removeHeader('Content-Length') before piping).

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Buffer size does not affect header validity; the error is about malformed header value, not size.

  2. 80% fail

    Even without buffering, nginx parses response headers; the invalid Content-Length is still detected.

  3. 90% fail

    This controls request body size, not response header validation.