Browser Cache policy

To improve site access speed, use caching for optimization. Caches are mainly divided into strong cache and negotiated cache.

Negotiate the cache

It is mainly divided into last-Modified and ETAG. The following code changes show the differences between caches. Let’s talk about negotiation caching. Last-modified indicates the date the file was modified. If the file is modified, it should be retrieved. Last-modified is a modified file generated based on the server’s time.

If we change the file we get it back, so status is 200

If you refresh it again, 304 will be returned, indicating that the cache is up to date and does not need to be updated. The request will ask about the time when the relevant file was Modified (if-modified-since)

request

The response

**ETag:** is a token that can be associated with a Web resource

If the file is replaced, a unique ETAG is generated.

The file before the replacement

The replaced file

PS: If multiple servers are used for load balancing, eTAG inconsistency may occur. Apache’s default ETag value is always determined by the Inode, Size, and last modified time of the file. We just need to remove the Inode

Strong cache

Strong caching is more thorough than negotiated caching, in which the browser does not make requests to the server.

** Strong caching :** is divided into expires and cache-control

Expires: Indicates an Expires that allows a client to not check (send a request) before that Expires, equivalent to max-age. But if both exist, they are overwritten by the max-age of cache-control. Format: Expires: a time, followed by a time or date, after which the cache Expires. Before sending a request, the browser checks whether the time is invalid. If not, the browser sends a request again.

When Apache expires_mod is enabled, the browser caches the resource after the first request.

Cache-control Cache-control is used in the HTTP response header to indicate which caching policy the proxy and UA are using. Such as:

  • No-cache indicates that this response cannot be used directly for subsequent requests (without checking with the server).
  • No-store: no cache (not stored in non-volatile media, if there is, try to remove, for sensitive information)
  • Public is for everyone to cache.
  • Private indicates that only UA can be cached

In cache-control, max-age is set to the maximum cache time. The cache is used during that time.

If no-cache is set to no-cache, no cache will be performed.

digression

Found during testing the browser cache with Apache. Without cache-control, the browser will choose which caches to use based on its own situation, as you can see here. Don’t be surprised if you discover during server configuration that you haven’t configured any caching information but that the browser caches resources.