Search code examples
cache-control

How to set cache-control to always check for updates but always fall back to cache if server is unreachable


I'm missing something trying to understand cache-control (e.g., from https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control).

How do I set up cache control to accomplish the following (I'll be using an .htaccess file):

  1. If client fetches a file, it should always store it in the cache.
  2. When client needs a file, it should always check to see if the file has been changed and download a new copy if it has changed.
  3. If the attempt to check fails -- e.g., server down or no Internet connection -- client should always use a cached copy if available, no matter how old. Any copy is better than none.

Solution

  • Use Cache-Control: no-cache and set the ETag header.

    1. The resource will be stored in the cache. This is true of any cache header other than no-store.
    2. no-cache tells the client that it must check with the server to see if the cached copy is valid. It does this by sending a conditional request, which requires that the cached response have an ETag (or Last-Modified) header.
    3. Using a cached copy of a resource when there's no connectivity is the default behavior. You could prevent this with the must-revalidate directive.