Why is Etag higher than last-modified?

1. How to set browser cache

  1. Expires (entity header field): The expiration time returned by the server, divided into "relative file last access time" and "absolute modification time". Disadvantages : What is returned is the server time, and the comparison is the client time. If it is inconsistent, an error may occur

  2. Cache-Control (common header field):

    • private
    • public
    • max-age=xxx: The cached content becomes invalid after xxx seconds
    • no-cache: Need to use another caching strategy to verify the cache (ETag, Last-Modified)
    • no-store: Do not cache
  3. **Last-Modified (**Entity header field):

    • After the browser requests the file, the server returns the last modification time of the file Last-Modified
    • The next request will carry the If-Modified-Since logo. If If-Modified-Since is equal to the server’s file modification time, it means that the file has not been modified and a 304 status code will be returned.
    • The browser reads the file from the browser cache. If If-Modified-Since is less than the file modification time of the server, the browser will resend the request to obtain the file and return the status code 200
  4. Etag (response header field): the unique identifier of the server file

    • The server returns the Etag field to the browser, and the Etag value will also change when the file changes
    • The next request will bring If-None-Match, which is the ETag value reserved by the browser. If a change is sent, the file is modified and a new request is required, and a 200 status code is returned.
    • Otherwise, the browser reads the file from the cache and returns a 304 status code

2. The difference between the four

  1. When Cache-Control is set to max-age=xx and Expires is set at the same time, Cache-Control has a higher priority
  2. When ETag and Last-Modified exist at the same time, the server will check ETag first, then Last-Modified, and finally decide whether to return 304 or 200

3. Why there is both last-modified and Etag

Consider the following situation:

  1. Some files may be changed periodically, but their content does not change (only the modification time of the change). At this time, we don't want the client to think that the file has been modified, and re-get
  2. Some files are modified very frequently, such as modification in less than a second (for example, N times in 1s), the granularity that If-Modified-Since can check is s-level, this modification cannot be judged (or (UNIX records MTIME can only be accurate to the second)
  3. The last modification time of the file that some servers cannot accurately obtain

So using Etag can more accurately control the cache.

Reference: I have stepped on the pit in an interview, and they are all here

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108481083