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 request the content-length is determined using these steps:

  1. A successful uncompressed request has a length equal to the size of the file.
  2. A successful compressed request has a length equal to the compressed size of the file.
  3. A successful request with no content — those with response code 201 or 204 — has a length of zero.
  4. A successful request for a range — with response code 206 — has a length equal to the number of bytes sent.
  5. An unsuccessful request does not have a content-length header.

With a HEAD request the content-length is determined using these steps:

  1. A request that would be successful has a length equal to the size of the file, irrespective of any content-encoding header.
  2. An unsuccessful request does not have a content-length header.

With a PUT request the content-length must be included in the request headers, and should be determined by the user-agent using these steps:

  1. A request without content-encoding should have a length equal to the size of the file.
  2. A request with content-encoding should have a length equal to the size of the compressed payload.
  3. A request to create an empty file should have a length of zero.

With a POST request the content-length must be included in the request headers, and should be determined by the user-agent as:

  1. The byte-count of the request body. Compression is not supported by the server with POST messages.

All requests with DELETE, 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 from 200 to 206.
  • The content-length header is omitted from any unsuccessful response, from 301 to 501.

Specifying the size of the payload