We are a software consultancy based in Berlin, Germany. We deliver
high quality web apps in short timespans.

Upstream Agile GmbH Logo

Http Caching assets in Rails 3.1

October 20, 2011 by Alex

I’ve been wrestling with this for the past few hours and finally got it working so I’m going to share this, hoping it might save others a few hours of their lives.

I’m currently working on a Rails 3.1 app that is being deployed to Heroku. We use the asset pipeline to serve all our assets and we want those to load fast. By default Rails sets ETag headers, which means that for every (web page) request the browser checks on all the assets, usually resulting in a 304 Not Modifed response from the server. It’s faster than serving the assets each time but it still means one round trip per asset. We can avoid this by setting an Expires headers with a far future date.

To do this add the following lines to your production.rb:

config.serve_static_assets = true
config.static_cache_control = "public, max-age=#{1.year.to_i}"
config.assets.compile = true
config.assets.digest = true

This will precompile the assets when you push the app to Heroku and set an Expires header with an expiry date 1 year in the future.

Don’t forget that you must reference your assets through the Rails asset helpers like asset_tag and image_tag (in *.scss files you can use image-url() etc. instead of the url() call that comes with CSS).

Hello Explorer!

You’ve found our very old Website Archive (2007-2012). It’s a bit out of date, but we love looking back at how it all started - and how far we’ve come since then! We’re now fully focused on building our coworking management product, Cobot.

Take a look →