I found a problem online today. For an online image domain name, CDN caching has been added to the front end. If the cache is not dropped, PHP is used to dynamically implement image scaling. However, after the image processed by PHP is output, it must be read from the backend every time, and the pressure on the backend server increases instantly. After analysis, there is no 304 processing in PHP.
The principle of HTTP is this. After each request to the server, the server detects whether there has been any modification. If there is no modification, it can directly return a 304 status code, so that the client's cache is used. This is the principle of CDN. , if 304 is set, the corresponding URL will be cached;
The relevant code is as follows:
Copy code The code is as follows:
//Check if there is any change
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){
$etag = $_SERVER['HTTP_IF_NONE_MATCH'];
If (md5($this->image) === $etag){
header("HTTP/1.1 304 Not Modified");
exit;
}
}
header("Last-Modified: " . gmdate("D, d M Y H:i:s", strtotime('2011-1-1'))." GMT");
//Output etag header
header('etag:' . md5($this->image));
header('Cache-Control:max-age=2592000');echo $this->image;
The http header HTTP_IF_NONE_MATCH is generally the identification of a certain URL returned by the server. It is generally calculated using MD5. In this way, we can check whether the MD5 value is correct. If it is the same, 304 can be returned;
PS:
I just grabbed the package for a long time, and I only saw the Etag tag returned by the server. I didn’t see the If-None-Match in the http header of the client, so I added the following code to fastcgi.conf.default:
Copy code The code is as follows:
fastcgi_param CACHE_ETAG $http_if_none_match;
When $_SERVER is printed, there is no CACHE_ETAG variable at all. It seems that nginx will put the relevant HTTP headers into the $_SERVER variable, which also deepens the understanding of the http protocol