Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caching image but update on change

I'm storing and caching images with link like this

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

Users have ability to modify and overwrite 1.jpg or 2.jpg. So what I want to cache all images but update the cache of that image file which is just over-written. Right now I'm using .htaccess method for cache

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

But using this method image still remains the same even if user overwrites the file.

like image 613
Basic Bridge Avatar asked Nov 11 '12 18:11

Basic Bridge


1 Answers

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

FileETag MTime Size

The ETag will effectively "expire" the cached image automatically when the image changes. The downside is that the browser still inquires about the resource with each request so it's a little less efficient than the expiration directives you used. On the other hand ETags avoid the problem you've described.

However, if you've 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 won't check it again for some time. You can hack around that by appending a trivial query string like ?cache=123 to the URL just to make it different (thus bypassing the cache). Then you can rely on the ETag mechanism in future.

like image 80
Magnus Avatar answered Oct 08 '22 16:10

Magnus