According to section 14.13 of the HTTP specification, the Content-Length header is the number of octets (8-bit bytes) in the body of a message. If the length can be determined prior to sending, it can be very useful to include it. The most important reason is that KeepAlive requests (when the same connection is used to fetch more than one object from the web server) work only with responses that contain a Content-Length header. In mod_perl we can write:
When using Apache::File, the additional set_content_length( ) method, which is slightly more efficient than the above, becomes available to the Apache class. In this case we can write:
The Content-Length header can have a significant impact on caches by invalidating cache entries, as the following extract from the specification explains:
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
It is important not to send an erroneous Content-Length header in a response to either a GET or a HEAD request.
Eric Cholet (Logilune) and
Stas Bekman (StasoSphere & Free Books).