Home >Backend Development >PHP Tutorial >How to solve the problem that images generated by PHP files cannot be cached by CDN_PHP Tutorial
This article mainly introduces the solution to the problem that the images generated by the PHP file cannot be cached by the CDN. The PHP generation here The picture refers to the picture whose src address is a PHP file. If CDN is not used, the pressure on the server will be very great. This article explains how to add CDN. Friends who need it can refer to it
I found a problem online today. For an online image domain name, a CDN cache 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 always fails. To read from the backend, the pressure on the backend server increases instantly. After analysis, it is found that 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 codes are as follows:
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;
Among them, 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, so that 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 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 the 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