$content_length

The variable $content_length contains the value of the 'Content-Length' HTTP header sent by the client, representing the size of the request body in bytes. — NGINX Core (HTTP)

$content_length NGINX Core (HTTP)

Description

The $content_length variable in NGINX provides the length of the request body that is included in the 'Content-Length' HTTP header. It is set only for requests where this header is present, typically in POST and PUT methods. If there is no 'Content-Length' header sent by the client, the variable will be empty. This variable is primarily useful for handling requests with known content sizes, allowing for conditional logic based on the size of incoming data. When processing requests, NGINX sets $content_length after parsing the headers of the incoming request. If the 'Content-Length' header is specified, it will hold the numeric value; however, if the header is absent or malformed, $content_length will not reflect a valid size. In practice, valid values for this variable are strictly non-negative integers, indicating the byte count of the request body. Developers often use this variable to impose size limits, log request sizes, or conditionally handle large payloads in a more efficient manner.

Config Example

http {
    server {
        listen 80;

        location /upload {
            if ($content_length > 10000) {
                return 413;  # Request entity too large
            }
        }
    }
}

Subsystem

http

Cacheable

Yes

Contexts

http, server, location, if

Ensure that the 'Content-Length' header is actually present; otherwise, $content_length will be empty.

$content_length is only useful for methods such as POST and PUT where a body is usually present; for GET requests, it will not be set.

Not all clients correctly use the 'Content-Length' header, which can lead to unexpected results. When absent, the variable will not yield the size.