How can I control max-age for particular files with Rails?

Go To


I have Rails serving my static assets. Most of them have hashes in their name and are served with far-future expiration dates. But for one file, I can't serve it with a hash in its name, so I need to control the expiration date.

I have this in my application.rb which applies to all static assets:

config.static_cache_control = "public, max-age=2592000"

Is there a way for me to have a different max-age for just one file? I know I can make a new middleware that comes after ActionDispatch::Static and changes the value for certain files (see this writeup)... but then this will run for every single request, even those which aren't static assets. Is there a more elegant solution?

2012-04-04 05:04
by John Bachir
Is it okay to do it at the server level? Potentially makes more sense there anyway - Andrew Marshall 2012-04-04 05:08
I don't have that option in this deployment (heroku) - John Bachir 2012-04-04 05:11
I'm using heroku too and this has always been a burning question - Ashitaka 2012-04-04 13:15
the Rack::Static solution here is working for me - John Bachir 2012-04-04 19:22


A bad technique can be to fix the URL of your file in your route.rb. You can define a Controller to this route fixing the cache_control you want and use send_data method to server the file.

2012-04-04 08:14
by shingara
considered something like that as well... a messy path to go down but possibly the best solution in the en - John Bachir 2012-04-04 19:22
it's the most simplest if you don't want add a Middleware. Or you need hack the ActionDispatch::Static middleware to do the job. Maybe replace it by example - shingara 2012-04-05 07:42