Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force browsers to refresh cached, etaged images

User generated images on my site are served up by giving them a src like this:

userImage.ashx?id={UserId}&type=avatar

In the response from the ashx file, I set the etag header. When a user uploads a new image, the etag changes.

If the browser has a file cached with an etag, it should send a request to the server with the If-None-Match header set to that etag whenever it needs to display that file. If the cached etag is the same as the current etag on the server, the server responds with Not Modified - 304. If the etag is different, the server responds with OK - 200 and starts sending the new file.

This is how it should work in theory. However, I have found that for some browsers (firefox and IE, untested on others) this is not the case. If the user navigates to a new page with cached, etagged images, these browsers simply use the image out of their cache without making a request. If the user then refreshes the page, the browser sends a request with the If-None-Match header set.

So my problem is this: a user updates one of their images, then navigates to a page displaying the image. Until the user presses refresh, the cached image will be displayed, even though it has a different etag to the new image. When the user presses refresh, the browser does a request with the If-None-Match header set, which triggers the server to send the new image.

Is it possible to fix this?

Example 200 response header:

Status=OK - 200
Date=Thu, 27 Oct 2011 14:37:31 GMT
Server=Microsoft-IIS/6.0
X-Powered-By=ASP.NET
X-AspNet-Version=4.0.30319
Transfer-Encoding=chunked
Cache-Control=public, max-age=86400
Etag="27/10/2011 13:23:30"
Content-Type=image/jpg

Example 304 header:

Status=Not Modified - 304
Connection=close
Date=Thu, 27 Oct 2011 14:39:12 GMT
Server=Microsoft-IIS/6.0
X-Powered-By=ASP.NET
X-AspNet-Version=4.0.30319
Cache-Control=public, max-age=86400

(Using last modfied date as etag as its more adaptable for later needs regarding compression etc.)

like image 762
Oliver Avatar asked Nov 05 '22 12:11

Oliver


1 Answers

IIRC you can set how long a file is valid via the "Expires" header. So if you say "This file is valid for the next two days", the browser has no reason to contact your server.

max-age as given in your example does the same thing, basically.

like image 147
Johan B.W. de Vries Avatar answered Nov 09 '22 09:11

Johan B.W. de Vries