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
201
or204
— 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-length
header.
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-encoding
header. - An unsuccessful response does not have a
content-length
header.
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-encoding
should have a length equal to the size of the uncompressed request body. - A request with
content-encoding
should have a length equal to the size of the compressed request body. - A request to
PUT
an 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-length
header is present on every successful response from200
to207
. - The
content-length
header is omitted from any unsuccessful response, from301
to501
.