Search code examples
httphttp-headerslast-modifiedhttp2

Invalidate already-stored responses with Last-Modified header


Section 4 of RFC 7234 has this paragraph:

When more than one suitable response is stored, a cache MUST use the most recent response (as determined by the Date header field). It can also forward the request with "Cache-Control: max-age=0" or "Cache-Control: no-cache" to disambiguate which response to use.

It mentioned about invalidating already-stored responses with Date or Cache-Control headers.

What's about the Last-Modified header? Can I use it for the same purpose?


Solution

  • Last-Modified serves as a validator. These are mentioned earlier in the section you quoted:

    When presented with a request, a cache MUST NOT reuse a stored response, unless […] the stored response is either:

    • fresh (see Section 4.2), or
    • allowed to be served stale (see Section 4.2.4), or
    • successfully validated (see Section 4.3).

    Section 4.3 explains validation in detail. I think 4.3.2 is of must interest to you:

    [A] request containing an If-Modified-Since header field indicates that the client wants to validate one or more of its own stored responses by modification date. A cache recipient SHOULD generate a 304 (Not Modified) response (using the metadata of the selected stored response) if one of the following cases is true:

    1. the selected stored response has a Last-Modified field-value that is earlier than or equal to the conditional timestamp; 2. no Last-Modified field is present in the selected stored response, but it has a Date field-value that is earlier than or equal to the conditional timestamp; or, 3. neither Last-Modified nor Date is present in the selected stored response, but the cache recorded it as having been received at a time earlier than or equal to the conditional timestamp.

    So yes, it is perfectly in line with the RFC to do so. Since Last-Modified/If-Modified-Since is a pretty old mechanism that got introduced as early as HTTP/1.0, you can expect caches to comply.