ClickAider

Enabling browser caching of static resources in Rails

I was surprised to find that most out-of-the-box configurations for Rails and Apache are not set up to allow the browser to cache static resources like Javascript and images. This leads to slower page load times and bad looking rendering.

On Apache, this is very easy to fix using mod_expires.  I simply added the two highlighted lines below to our site configuration file in conf.d.  The Rails helpers like image_tag automatically appends a timestamp to the resource URLs, so updated versions of the resources will correctly be fetched by the browser even when an older version is cached.

<Directory "/var/www/example/public">
  Options FollowSymLinks
  Order allow,deny
  Allow from all
  ExpiresActive on
  ExpiresDefault "access plus 10 years"
</Directory>

2 Comments so far
Leave a comment

I made this change to my Apache configuration a couple of weeks ago, and have received quite a few reports that none of my pages load the current version when changes are made (the content is frequently updated).

I’ve reverted the change.

If you make this change, you need to ensure that static resources are always referred to by the rails helpers (e.g. image_tag, *not* img), or that you change the resource URLs whenever you update the content.

The rails helpers will always append a timestamp to its URLs to ensure that the latest version is fetched.


Leave a comment

(required)

(required)