HTTP caching
èç±éè¤ä½¿ç¨å ååéçè³æºï¼ç¶²ç«èç¶²é æç¨ç¨å¼è½å¤ 顯èå°æåæè½ãcaching å¯ä»¥æ¸å°ç¶²è·¯å³è¼¸é以éä½ä¸åè³æºå¯å±ç¤ºç延鲿éãåç¨ HTTP caching å¯ä»¥è®ç¶²ç«å¯ä»¥åææ´å¤è«æ±ã
ä¸å種é¡çå¿«å
å¿«åæ¯ä¸ç¨®å²å伺æå¨å復çè¨æ¯ä¸ç¨æ¤åæªåè¦çµ¦è«æ±è çæè¡ãç¶å¿«å伺æå¨æåè ä¸ä»½è«æ±æªæ¡çåè¦ï¼å¿«å伺æå¨æææªæ¤è«æ±è¨æ¯ï¼åè¦çµ¦è«æ±è åå¨å¿«åä¸çæªæ¡ï¼è䏿¯å¾è«æ±è è«æ±çç¶²é 伺æå¨å»è«æ±åå§æªæ¡ã鿍£çé使©å¶è½éæä¸åå¹¾åç®ç:è®ç¶²é 伺æå¨ä¸ç¨èçæ¯åå¾å®¢æ¶ç«¯ç¼åºçè«æ±ï¼æ¸è¼æ©å¨éä½çè² æãä¸ç±æ¼å³è¼¸èµ·é»è·é¢æ´æ¥è¿è«æ±ç«¯ï¼è½è®æ´é«è«æ±çéç¨æè½æ´å ï¼æ´é«è«æ±éè¦æ´å°çæéå³éè³æºãå°ä¸åè¦éæé«æè½çç¶²ç«ä¾è¬ï¼å¿«åä¸åå¾éè¦çä¸å¡ãå¦ä¸æ¹é¢ä¾è¬ï¼å¿«åçè«æ±ãå復ãå²åæ©å¶å¿ é è¨å®å¥½ï¼å¥è®åå¨å¿«å伺æå¨çæªæ¡é½æ¯åä¸å:éè¦çæ¯ç¶è³æºæ¹è®æå»ä½¿ç¨å¿«åï¼è䏿¯ä¸ç´åæ¾èã
å¿«åæå¥½å¹¾ç¨®ï¼ä½ä»åå¯ä»¥åçºå ©å¤§é¡:å ±ç¨åç§æçå¿«åãå ±ç¨çå¿«åå®ç¾©æ¯æå¿«å伺æå¨ä¸åçåè¦è½çµ¦å¥½å¹¾åä¸åçè«æ±è æåãèç§æçå¿«åå°±ç¸å°åªææåä¸åè«æ±è ãæ¤é é¢è¬å°çå¿«å大é¨å齿¯æä»£ç伺æå¨åç覽å¨çå¿«åï¼ä½æ¯å¿«åéæåæ¯ééå¨å¿«åãCDN å¿«åãåå代ç伺æå¨å¿«å ãè² è¼å¹³è¡¡å¨å¿«åï¼å®å齿¯é¨å±¬å¨ç¶²é 伺æå¨é£éï¼è®ç¶²ç«åç¶²é æç¨ç¨å¼æ´å ç©©å®ï¼æè½æ´å¥½ï¼ä¸ææ´å¥½çæ´å¢å§ã

ç覽å¨ç§æçå¿«å
ç§æçå¿«ååªææåä¸å使ç¨è ãä½ å¯è½å·²ç¶å¨è¨å®ç覽å¨çæåçéå¿«åäºãä¸åç覽å¨å¿«åæåæ¾ææéé HTTP åå®ä¸è¼çæªæ¡ãéé¡åçå¿«åæ¯çºäºæ¹ä¾¿ä½¿ç¨è ä¸ä¸é ç§»åãåæªãæè æª¢è¦æªæ¡åå§ç¢¼ççï¼è®ä½¿ç¨è ä¸ç¨å次ååå§ä¼ºæå¨è«æ±æªæ¡ãæ¤æ©å¶å樣çå¢é²ç·ä¸ç覽快åã
代ç伺æå¨çå ±ç¨å¿«å
ä¸åå ±ç¨çå¿«å伺æå¨ï¼æ¯æå¿«ååæ¾è è½è®å¤ä½ä½¿ç¨è è«æ±çæªæ¡å¯æ¬ãèä¾ä¾èªªï¼ISP æè ä½ çå ¬å¸å §é¨ç¶²è·¯å¯è½æè¨ç½®ä»£ç伺æå¨ï¼ç¨ä¾æåæ¯å使ç¨è ï¼è®ä¸äºè¼å¸¸ç¨çæªæ¡å¯ä»¥éè¤ä½¿ç¨å¤æ¬¡ï¼æ¸å°ç¶²è·¯äº¤éçæµéã
Targets of caching operations
HTTP caching is optional, but reusing a cached resource is usually desirable. However, common HTTP caches are typically limited to caching responses to GET and may decline other methods. The primary cache key consists of the request method and target URI (oftentimes only the URI is used as only GET requests are caching targets). Common forms of caching entries are:
- Successful results of a retrieval request: a
200(OK) response to aGETrequest containing a resource like HTML documents, images or files. - Permanent redirects: a
301(Moved Permanently) response. - Error responses: a
404(Not Found) result page. - Incomplete results: a
206(Partial Content) response. - Responses other than
GETif something suitable for use as a cache key is defined.
A cache entry might also consist of multiple stored responses differentiated by a secondary key, if the request is target of content negotiation. For more details see the information about the Vary header below.
æ§å¶å¿«å
>Cache-control æªé
Cache-Control æ¯ HTTP/1.1 ç¨ä¾ç¹å¥æä»¤å¿«åå¦ä½èçåè¦åè¦æ±çéç¨æªé æ¬ä½ãä½¿ç¨æ¤æ¬ä½åå¤ç¨®çæä»¤ï¼ä¾å®ç¾©ä½ çå¿«åæ©å¶ã
ä¸è¦åä»»ä½å¿«å
å¿«åä¸è©²ååä»»ä½ç使ç¨è è«æ±æè 伺æå¨çåè¦ãæ¯åè«æ±é½æ¯éå°åå§ç伺æå¨å»åå¾è³æºã
Cache-Control: no-store
å¿«åéååï¼ä½æ¯è¦éæ°é©è
å¿«å伺æå¨å¨æå·²å²åçè¤è£½çæ¬å³çµ¦è«æ±è ä¹åï¼å æéä¸åè«æ±çµ¦ç¶²é 伺æå¨åé©èã
Cache-Control: no-cache
ç§ææå ±ç¨çå¿«å
å ±ç¨(Public)éåæä»¤æåºæ¤åè¦è¨æ¯å¯ä»¥ç±ä»»ä½å¿«å給ååãéé»å¯ä»¥è®æå¾æç¨èï¼åå¦é 颿ä¸å®¹æå¿«åæåç HTTP é©èçè¨æ¯æè åè¦çæ 碼ï¼ç¾å¨æè©²å¾å®¹æè¢«ååäºã
ç¸å°çï¼ç§æ(Private)çæä»¤æç¤ºå¿«ååªçµ¦ä¸å使ç¨è 使ç¨ï¼ä¸ä¸è½è¢«å ±ç¨çå¿«å伺æå¨çµ¦å²åéãé±ç§è¦çª(ç¡ç模å¼)çå¿«åå°±å¯è½æ¯é樣åã
Cache-Control: private Cache-Control: public
æææé
å¨é裡æéè¦çæä»¤å°±æ¯"max-age=<seconds>" ï¼æææ¯æåæ¾å¨å¿«å伺æå¨ä¸çè³æºæå©ä¸å¤å°æé被èªå®éæ¯æ°é®®çã è·Expiresä¸å¤ªä¸æ¨£ï¼éåæªé æ¬ä½å¿«åæçæ¯è«æ±æ¤åè¦çæ¥æåæéãå°æ¼ç¨å¼ä¸ä¸å¸¸æ´æ°çæªæ¡ï¼ä½ å¯ä»¥ç©æ¥µå°ä½¿ç¨æ¤æ©å¶ãéäºæªæ¡å
å«äºï¼åæªãCSSãJavascripts æªæ¡ççã
æ³è¦äºè§£æ´å¤ç話ï¼è«åè¦ä¸é¢çFreshnessã
Cache-Control: max-age=31536000
é©è
ç¶ä½¿ç¨"must-revalidate"æä»¤æï¼å¿«å伺æå¨ä¸å®è¦å
ç¼éè«æ±è¨æ¯çµ¦ç¶²é 伺æå¨é©èï¼è«å·²ç¶ç¢ºèªæ¯éæææé䏿ªæ¡ææ´æ°çåè¦ç話ï¼èçæªæ¡å°±ä¸è½ä½¿ç¨ãå妿³äºè§£æ´å¤ï¼è«åè¦ä¸é¢çValidationã
Cache-Control: must-revalidate
Pragmaæªé æ¬ä½
Pragma æ¯ HTTP/1.0 çæªé æ¬ä½ï¼æ¤æªé æ¬ä½æ²æç¹å¥ææ¯ HTTP åè¦æéº¼èçï¼æä»¥ç¨æ¤ä¾å代 HTTP/1.1 Cache-Controléç¨æªé æ¬ä½ä¸¦ä¸æ¯å¾ç©©å®ãåå¦Cache-Control æªé æ¬ä½å¨å³éè«æ±è¨æ¯æè¢«çç¥æäºï¼æ¤æªé æ¬ä½éä½ççµæè· Cache-Control: no-cache䏿¨£ãæ¤Pragmaæ¬ä½åªè½è· HTTP/1.0 çè«æ±è
使ç¨ã
Freshness
Once a resource is stored in a cache, it could theoretically be served by the cache forever. Caches have finite storage so items are periodically removed from storage. This process is called cache eviction. On the other side, some resources may change on the server so the cache should be updated. As HTTP is a client-server protocol, servers can't contact caches and clients when a resource changes; they have to communicate an expiration time for the resource. Before this expiration time, the resource is fresh; after the expiration time, the resource is stale. Eviction algorithms often privilege fresh resources over stale resources. Note that a stale resource is not evicted or ignored; when the cache receives a request for a stale resource, it forwards this request with a If-None-Match to check if it is in fact still fresh. If so, the server returns a 304 (Not Modified) header without sending the body of the requested resource, saving some bandwidth.
Here is an example of this process with a shared cache proxy:

The freshness lifetime is calculated based on several headers. If a "Cache-Control: max-age=N" header is specified, then the freshness lifetime is equal to N. If this header is not present, which is very often the case, it is checked if an Expires header is present. If an Expires header exists, then its value minus the value of the Date header determines the freshness lifetime.
Heuristic freshness checking
If an origin server does not explicitly specify freshness (e.g. using Cache-Control or Expires header) then a heuristic approach may be used.
In this case look for a Last-Modified header. If this header is present, then the cache's freshness lifetime is equal to the value of the Date header minus the value of the Last-modified header divided by 10. The expiration time is computed as follows:
expirationTime = responseTime + freshnessLifetime - currentAge
where responseTime is the time at which the response was received according to the browser. For more information see RFC 7234: Hypertext Transfer Protocol (HTTP/1.1): 4.2.2. Calculating Heuristic Freshness.
Revved resources
The more we use cached resources, the better the responsiveness and the performance of a Web site will be. To optimize this, good practices recommend to set expiration times as far in the future as possible. This is possible on resources that are regularly updated, or often, but is problematic for resources that are rarely and infrequently updated. They are the resources that would benefit the most from caching resources, yet this makes them very difficult to update. This is typical of the technical resources included and linked from each Web pages: JavaScript and CSS files change infrequently, but when they change you want them to be updated quickly.
Web developers invented a technique that Steve Souders called revving[1]. Infrequently updated files are named in a specific way: in their URL, usually in the filename, a revision (or version) number is added. That way each new revision of this resource is considered as a resource on its own that never changes and that can have an expiration time very far in the future, usually one year or even more. In order to have the new versions, all the links to them must be changed, that is the drawback of this method: additional complexity that is usually taken care of by the tool chain used by Web developers. When the infrequently variable resources change they induce an additional change to often variable resources. When these are read, the new versions of the others are also read.
This technique has an additional benefit: updating two cached resources at the same time will not lead to the situation where the out-dated version of one resource is used in combination with the new version of the other one. This is very important when web sites have CSS stylesheets or JS scripts that have mutual dependencies, i.e., they depend on each other because they refer to the same HTML elements.

The revision version added to revved resources doesn't need to be a classical revision string like 1.1.3, or even a monotonously growing suite of number. It can be anything that prevent collisions, like a hash or a date.
Cache validation
When a cached document's expiration time has been reached, it is either validated or fetched again. Validation can only occur if the server provided either a strong validator or a weak validator.
Revalidation is triggered when the user presses the reload button. It is also triggered under normal browsing if the cached response includes the "Cache-Control: must-revalidate" header. Another factor is the cache validation preferences in the Advanced->Cache preferences panel. There is an option to force a validation each time a document is loaded.
ETags
The ETag response header is an opaque-to-the-useragent value that can be used as a strong validator. That means that a HTTP user-agent, such as the browser, does not know what this string represents and can't predict what its value would be. If the ETag header was part of the response for a resource, the client can issue an If-None-Match in the header of future requests â in order to validate the cached resource.
Last-Modified
The Last-Modified response header can be used as a weak validator. It is considered weak because it only has 1-second resolution. If the Last-Modified header is present in a response, then the client can issue an If-Modified-Since request header to validate the cached document.
When a validation request is made, the server can either ignore the validation request and respond with a normal 200 OK, or it can return 304 Not Modified (with an empty body) to instruct the browser to use its cached copy. The latter response can also include headers that update the expiration time of the cached document.
Varying responses
The Vary HTTP response header determines how to match future request headers to decide whether a cached response can be used, or if a fresh one must be requested from the origin server.
When a cache receives a request that has a Vary header field, it must not use a cached response by default unless all header fields specified in the Vary header match in both the original (cached) request and the new request.
This feature is commonly used to allow a resource to be cached in uncompressed and (various) compressed forms, and served appropriately to user agents based on the encodings that they support. For example, a server can set Vary: Accept-Encoding to ensure that a separate version of a resource is cached for all requests that specify support for a particular set of encodings, e.g. Accept-Encoding: gzip,deflate,sdch.
Vary: Accept-Encoding
å註ï¼Use Vary with careâit can easily reduce the effectiveness of caching! A caching server should use normalization to reduce duplicated cache entries and unnecessary requests to the origin server. This is particularly true when using Vary with headers and header values that can have many values.
The Vary header can also be useful for serving different content to desktop and mobile users, or to allow search engines to discover the mobile version of a page (and perhaps also tell them that no Cloaking is intended). This is usually achieved with the Vary: User-Agent header, and works because the User-Agent header value is different for mobile and desktop clients.
Vary: User-Agent
Normalization
As discussed above, caching servers will by default match future requests only to requests with exactly the same headers and header values. That means a request will be made to the origin and a new cache will be created for every slight variant that might be specified by different user-agents.
For example, by default all of the following result in a separate request to the origin and a separate cache entry: Accept-Encoding: gzip,deflate,sdch, Accept-Encoding: gzip,deflate, Accept-Encoding: gzip. This is true even though the origin server will probably respond with â and store â the same resource for all requests (a gzip)!
To avoid unnecessary requests and duplicated cache entries, caching servers should use normalization to pre-process the request and cache only files that are needed. For example, in the case of Accept-Encoding you could check for gzip and other compression types in the header before doing further processing, and otherwise unset the header. In "pseudo code" this might look like:
// Normalize Accept-Encoding
if (req.http.Accept-Encoding) {
if (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
}
// elsif other encoding types to check
else {
unset req.http.Accept-Encoding;
}
}
User-Agent has even more variation than Accept-Encoding. So if using Vary: User-Agent for caching mobile/desktop variants of files you'd similarly check for the presence of "mobile" and "desktop" in the request User-Agent header, and then clear it.
See also
- RFC 7234: Hypertext Transfer Protocol (HTTP/1.1): Caching
- Caching Tutorial â Mark Nottingham
- HTTP caching â Ilya Grigorik
- RedBot, a tool to check your cache-related HTTP headers.