Cache-Control
Cache-Control is the most important rule. This field is used to specify the commands that all cache mechanisms must obey throughout the request/response chain. These commands are used to prevent the cache from adversely interfering with requests or responses. These commands usually overwrite the default cache algorithm. Cache commands are one-way, that is, there is a command in the request does not mean that the same command will exist in the response.
The definition of cache-control is: Cache-Control = "Cache-Control" ":" cache-direve VE. Table 1 shows applicable values.
Table 1. Common cache-direve VE values
| Cache-directive |
Description |
| Public |
All content will be cached |
| Private |
Content is only cached in private cache |
| No-cache |
All content will not be cached |
| No-store |
All contents are not cached in the cache or temporary Internet files. |
| Must-revalidation/proxy-revalidation |
If the cached content is invalid, the request must be sent to the server/proxy for reverification. |
| Max-age = xxx (xxx is numeric) |
The cached content will expire after xxx seconds. This option is only available in HTTP 1.1 and has a higher priority if used together with Last-Modified. |
When the client sends a Request for a URL for the first time through a browser, the browser will send the Header (HTTP Request Header) to the server according to the Http protocol ), when the server responds with the Http Reponse Header, the server returns 200 in the following format:
| The code is as follows: |
Copy code |
HTTP/1.1 200 OK Date: Tue, 03 Mar 2009 04:58:40 GMT Content-Type: image/jpeg Content-Length: 83185 Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT Cache-Control: max-age = 2592000 Expires: Thu, 02 Apr 2009 05:14:08 GMT Etag: "5d8c72a5edda8d6a: 3239 & Prime; |
When the client requests this URL for the second time, according to the HTTP protocol, the browser will send an Http Request Header to the server. The server responds and records that the relevant record property tag file has not been changed, the server returns 304, which is directly read from the cache:
| The code is as follows: |
Copy code |
HTTP/1.x304 Not Modified Date: Tue, 03 Mar 2009 05:03:56 GMT Content-Type: image/jpeg Content-Length: 83185 Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT Cache-Control: max-age = 2592000 Expires: Thu, 02 Apr 2009 05:14:08 GMT Etag: "5d8c72a5edda8d6a: 3239 & Prime; |
I. Working principles of Last-Modified, Expires, and Etag
1. Last-Modified
When the browser requests a URL for the first time, the server returns 200, the content is the resource you requested, and there is a Last-Modified attribute mark (Http Reponse Header) the last modification time of this file on the service end. The format is similar to this:
1 Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT
When the client requests this URL for the second time, the browser will send the If-Modified-Since Header (HTTP Request Header) to the server according to the Http protocol ), check whether the file has been modified after this time:
1 If-Modified-Since: Tue, 24 Feb 2009 08:01:04 GMT
If the resources on the server are Not Changed, the HTTP 304 (Not Changed.) status code is automatically returned and the content is blank, which saves the amount of data transmitted. When the server code changes or the server is restarted, the resource is re-issued, and the returned result is similar to the first request. This ensures that resources are not repeatedly sent to the client, and that the client can obtain the latest resources when the server changes.
Note: If the time of If-Modified-Since is later than the current time of the server (the current request time request_time), it is regarded as an invalid request.
2. Working principles of Etag
The HTTP specification description defines ETag as the object tag of the requested variable (see 14.19 ).
Simply mark the request URL when the server responds and send it to the client in the HTTP response header, similar to the format returned by the server:
1 Etag: "5d8c72a5edda8d6a: 3239 & Prime;
The query update format of the client is as follows:
1 If-None-Match: "5d8c72a5edda8d6a: 3239 & Prime;
If ETag does not change, status 304 is returned.
That is, after the client sends a request, the Http Reponse Header contains Etag: "5d8c72a5edda8d6a: 3239 & Prime;
ID, indicating that the Client has the ID: 5d8c72a5edda8d6a: 3239.
When the next Request is sent to Request the same URI, the browser simultaneously sends an If-None-Match Header (Http Request Header). At this time, the Header contains the Etag obtained from the previous access: "5d8c72a5edda8d6a: 3239 & Prime; identifier.
1 If-None-Match: "5d8c72a5edda8d6a: 3239 & Prime;
In this way, the Client is equal to two copies of the Cache, and the server compares the etag of the two. If-None-Match is False and 200 is Not returned, 304 (Not Modified) Response is returned.
3. Expires
After the given date/time, the response is considered obsolete. For example, Expires: Thu, 02 Apr 2009 05:14:08 GMT
It must be used in combination with Last-Modified. It is used to control the validity period of the request file. When the request data is within the validity period, the client browser requests the data from the cache instead of the server. When the data in the cache expires or expires, it is decided to update the data from the server.
4. Last-Modified and Expires
The Last-Modified Mark can save a little bandwidth, but it still cannot escape sending an HTTP request and must be used with Expires. However, the Expires mark does not allow the browser to send HTTP requests. For example, when you press F5 or click the Refresh button, even if there is an Expires URI, in the same way, an HTTP request is sent out. Therefore, the Last-Modified is still used, and it must be used with Expires.
5. Etag and Expires
If both Etag and Expires are set on the server, the Etag principle is the same, that is, the Http Request Header: If-Modified-Since and If-None-Match corresponding to Last-Modified/Etag. We can see that the values of these two headers are exactly the same as those of Last-Modified and Etag sent by the Web Server; if-Modified-Since and If-None-Match are completely matched, that is, after checking the modification time and Etag, the server can return 304.
6. Last-Modified and Etag
The http header of the Last-Modified and ETags requests is used together. The server first generates the Last-Modified/Etag mark. The server can use it later to determine whether the page has been Modified, to determine whether the file is cached.
The process is as follows:
1. The client requests A page ().
2. The server returns to page A and adds A Last-Modified/ETag to page.
3. The client displays the page and caches the page together with Last-Modified/ETag.
4. The customer requests page A again and passes the Last-Modified/ETag returned by the server in the Last request to the server.
5. The server checks the Last-Modified or ETag and determines that the page has not been Modified since the Last client request. The server returns the response 304 and an empty response body.
Note:
1. The Last-Modified and Etag headers are both Http Reponse headers sent by the Web Server. The Web Server should support both headers.
2. After the Web Server sends the Last-Modified/Etag headers to the client, the client caches these headers;
3. When the client initiates a Request for the same page again, it will send the Http Request Header: If-Modified-Since and If-None-Match corresponding to Last-Modified/Etag respectively. We can see that the values of these two headers are exactly the same as those of Last-Modified and Etag sent by the Web Server;
4. Check with the server to determine whether the file continues to be cached;
2. Processing of Epires and Etag on dynamic pages with non-real-time interaction
You can consider caching data that is not updated frequently, such as tag classification and archiving. Simply put, the expires and etag identifiers are output in dynamic programs with non-real-time interaction, so that they can be cached. However, you must disable the session to prevent the http header from containing the session id during http response;
3.1. Expires
For example, expires. php
| The code is as follows: |
Copy code |
Header ('cache-Control: max-age = 86400, must-revalidate '); Header ('last-Modified: '. gmdate ('d, d m y h: I: s'). 'Gmt '); Header ("Expires:". gmdate ('d, d m y h: I: S', time () + '2017 & prime;). 'Gmt '); |
3.2. Etag
Processing is based on the Http return status. When 304 is returned, it is directly read from the cache.
For example, etag. php
| The code is as follows: |
Copy code |
Cache (); Echo date ("Y-m-d H: I: s "); Function cache () { $ Etag = http://longrujun.name "; If (isset ($ _ SERVER ['http _ IF_NONE_MATCH ']) & $ _ SERVER ['http _ IF_NONE_MATCH '] = $ etag) { Header ('etag: '. $ Etag, true, 304 ); Exit; } Else header ('etag: '. $ Etag ); } |
Image Cache instance
| The code is as follows: |
Copy code |
$ ImagePath = "path/to/some/image "; $ ETag = $ imagePath; $ ETag. = fileMTime ($ imagePath ); $ ETag = md5 ($ eTag ); If (isset ($ _ SERVER ['http _ IF_NONE_MATCH ']) & (Stripslashes ($ _ SERVER ['http _ IF_NONE_MATCH ']) = $ eTag )){ Header ("HTTP/1.1 304 Not Modified", TRUE, 304 ); Exit (); } Header ("ETag:". $ eTag ); Header ("Content-Type: image/png "); ReadFile ($ imagePath ); Exit ();
|
The above method is super simple. Let's take a look at a complete instance.
| The code is as follows: |
Copy code |
$ Fullpath = '/www/images/'. basename ($ _ GET ['IMG ']); // assume that all files are under/www/images/. If (! Is_file ($ fullpath )){ Header ("HTTP/1.0 404 Not Found "); Exit (); } $ Info = getImageSize ($ fullpath); // Obtain image information If (! $ Info) {// if it is not an image Header ("HTTP/1.0 404 Not Found "); Exit (); } // All the following header functions are output header information. Many. Header ('content-type: '. $ info ['Mime']); // similar to image/png Header ('content-Length: '. filesize ($ fullpath); // file Length Header ('pragma: '); // useless, but it must be set to prevent the server from generating terrible no-cache words // Manually set the Expiration Time, in seconds $ Validtime = 48*60*60; // 48 hours // Cache relative request time, Header ('cache-Control: '. 'Max-age ='. $ validtime ); // Also an important Expires header. Its function is similar to max-age. // Time () + $ validtime: Set the Expiration time. Requests will be submitted to the server only after expiration. // Gmdate, which generates a string of Sun, 01 Mar 2009 04:05:49 + 0000 and is the GMT standard time zone // Preg_replace, which generates Sun, 01 Mar 2009 04:05:49 GMT. Note: It may be related to server settings, // But I use the default settings Header ('expires: '. preg_replace ('/. {5} $/', 'gmt', gmdate ('R', time () + $ validtime ))); // Last file modification time $ Lasttime = filemtime ($ fullpath ); // Set the last modification time. When you click refresh, the browser requests the image again to send the 'If _ MODIFIED_SINCE 'header, // Read by the php program Header ('last-Modified: '. preg_replace ('/. {5} $/', 'gmt', gmdate ('R', $ lasttime ))); // Important. If the request time is the same as the file generation timestamp, the file is not modified and the client can cache the file. If (strtotime ($ _ SERVER ['http _ IF_MODIFIED_SINCE ']) = $ lasttime ){ Header ("HTTP/1.1 304 Not Modified"); // The server sends commands that have Not been Modified Exit (); } // If the file is modified, you have to re-send the data Echo file_get_contents ($ fullpath ); |