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).