Fixing Mongrel's Page Caching

Posted February 3rd, 2008 in [Solutions]

While playing around with Rails page caching, we discovered a peculiar quirk. Any pages set to be cached are saved as static HTML files, but Mongrel doesn’t seem to be able to find them and continues to process subsequent requests dynamically. This only happens though if you change the Rails’ page cache directory in your application configuration. Upon digging further, here’s what we uncovered.

By default, Rails will cache files in /public, and this works fine if you enable caching in your development environment. However, with a different cache location, such as


config.action_controller.page_cache_directory = RAILS_ROOT + "/tmp/cache"

things no longer work as expected. It turns out that Mongrel completely ignores this setting when looking for cached content. Furthermore, Mongrel’s directory handler assumes that files will always be located under /public.

If you want to patch this up on your local machine, just apply this Mongrel patch.

Page Caching Tips

Here’s some useful info if you’re implementing page caching in Ruby on Rails.

  • Using Mongrel to read cached pages is fine for development and POC’s but your best bet is to put this responsibility into the hands of an HTTP front-end such as Apache or Nginx.
  • If you want to cache every view in a controller, instead of adding “caches_page” for each action, just add this line near the top of your controller:

after_filter { |c| c.cache_page}
  • If you’re caching pages in a password protected part of your site, a relatively painless solution is to configure Apache or Nginx to read an htpasswd file and handle authentication on the front-end. Alternately, you could use Rails 2.0’s basic authentication as part of a before_filter but this would only work with fragment caching (since full page caching ignores any controller filters completely).

Leave a Reply (Textile enabled)