Specifying the size of the payload
Content Length
Preliminaries
This note documents how the content-length header is determined and used in the exchange between browser and server.
The content-length header is simply the message payload's byte count. Any request that has a body should include this in the request headers, and every successful response — whether it has a payload or not — should include this in the response headers.
The content length is used as a basic sanity check to prevent bad actors from crafting illegitimate messages.
With a GET response the content-length is determined using these steps:
- A successful uncompressed response has a length equal to the size of the file.
- A successful compressed response has a length equal to the compressed size of the file.
- A successful response with no content — those with response code
201or204— has a length of zero. - A successful response for a range — with response code
206— has a length equal to the number of bytes sent. - An unsuccessful request does not have a
content-lengthheader.
With a HEAD response the content-length is determined using these steps:
- A response that would be successful has a length equal to the size of the file, irrespective of any
content-encodingheader. - An unsuccessful response does not have a
content-lengthheader.
With a PUT, PATCH, POST or DELETE requests the content-length must be included in the request headers, and should be determined by the user-agent using these steps:
- A request without
content-encodingshould have a length equal to the size of the uncompressed request body. - A request with
content-encodingshould have a length equal to the size of the compressed request body. - A request to
PUTan empty file should have a length of zero.
All requests with OPTIONS or TRACE methods do not expect a content length header in the request, and will not include it in the response.
Configuration
The server does not have any configurable options for content length.
Review
Key points to remember:
- The
content-lengthheader is present on every successful response from200to207. - The
content-lengthheader is omitted from any unsuccessful response, from301to501.
