Image caching but updating changes

I store and cache images with a link like this

http://example.com/1.jpg http://example.com/2.jpg 

Users can modify and overwrite 1.jpg or 2.jpg . So, I want to cache all images, but update the cache of this image file, which is just rewritten. I'm using the .htaccess method for the cache right now

 <IfModule mod_expires.c> ExpiresActive On <FilesMatch "(?i)^.*\.(jpg|jpeg|png)$"> ExpiresDefault "access plus 1 year" </FilesMatch> </IfModule> 

But the use of this method image remains unchanged even if the user overwrites the file.

+4
source share
2 answers

Go, the ETag should serve your needs without further effort. ETags should work by default, so you really don't need to do anything, but to avoid problems in multi-server environments, you can configure your ETags to calculate from file size and last timestamp. For example, replace existing directives with the following line in your .htaccess or Apache configuration:

 FileETag MTime Size 

The ETag effectively expires the cached image automatically when the image changes. The disadvantage is that the browser still requests a resource with each request, so it is slightly less efficient than the expiration directives used. ETags, on the other hand, avoid the described problem.

However, if you have already used one of the cache directives, as described in your question, and set the Expires value to something far in the future, then any browser that requested the file in the past will not check it again for some time. You can hack this by adding a trivial query string, such as ?cache=123 , to the url to make it different (thus bypassing the cache). Then you can count on the ETag mechanism in the future.

+4
source

The problem is most likely not on the server, but in the browser. Browsers do not check the server for image changes. What you have done does not completely solve this problem.

The following indicates that the browser always checks the server for changes.

 <IfModule mod_headers.c> <FilesMatch "(?i)^.*\.(jpg|jpeg|png)$"> Header set Cache-Control "max-age=0" </FilesMatch> </IfModule> 

Just be aware that this will make your site slower when accessing these images. Files will still be cached, but the browser will check the server to see if they have changed (If-Modifed-Since). Increase the maximum age (in seconds) to increase productivity due to stagnation.

(BTW, "max-age = 0, must-revalidate" is the best value, but browsers incorrectly implemented the specification. Must-revalidate may disable the cache in some browsers and proxies.)

See also fooobar.com/questions/14789 / ...

+1
source

Source: https://habr.com/ru/post/1445372/


All Articles