followup on conditional page caching

A reader of my blog entry conditional use of page cache in Rails pointed out some problems with the caching behaviour. Thanks Dan!

The problem could occur because the “page cached” version of a page is served by the web server directly, and not by Rails, so it may have HTTP cache headers as defined by the web server for a static file.

If a user first views the “page cached” version, and then logs in to the system and views the same page, the browser may decide that it can use the cached version, without making a new request to the server.

I’ve made a fix to this for my Apache setup, by expanding my .htaccess rules to this:

RewriteRule ^$ index.html [QSA]
RewriteCond %{HTTP_COOKIE} !^.*logged_in=yes.*$
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

Header set Cache-Control “no-cache”

The Header directive is forcing Apache to include the Cache-Control: no-cache header on the static HTML files (i.e. the “page cached” files), which means the browser will always make a request to the server rather than using a locally cached version1.

I’ve read around this problem a bit, and I think the no-cache setting is an appropriate one to use in this situation.

It does mean that we are reducing the cachability of ‘public’ pages, which is a shame. Having thought about this whole problem some more, I do wonder if it would be easier to just have different URL paths for ‘public’ and ‘logged in’ views. Doing that would make it easier to have different caching behaviour for each. However, I’m sticking with my current solution, because I like the way that a given URL represents a single resource2, and the fact that some of the display changes if a user is logged in shouldn’t change the semantics3.

1 Except Safari, apparently. I don’t have my own Safari available to test with.

2 In my application, a Band, Gig or Venue.

3 Though looking at URLs, mine could be improved, since they are currently using the default Rails ID numbers, which don’t mean very much.

Post a Comment

Your email is never published nor shared. Required fields are marked *