Setting Default HTTP Cache Headers in Rails
Oct 25, 2013
1 minute read

We’re working on putting our current product behind Amazon Cloudfront. With Cloudfront, if you don’t set a Cache-Control header with an expiry time, Cloudfront will cache the content for 24 hours by default. Instead of littering all my controller actions with cache settings, I wanted to add a default value then be able to override on and action by action basis.

First, here’s how you actually set a cache-control header. This would go in a controller action.

expires_in 1.minute, :public => true

To add a default setting, add the expires_in call to a before_filter in your application controller.

class ApplicationController < ActionController::Base
  before_filter :set_default_cache_headers

  def set_default_cache_headers
    expires_in 1.minute, :public => true

Finally, override the cache header as needed in your controller actions.

class HomeController < ApplicationController
  def index
    # ... action logic
    expires_in 5.minute, :public => true

comments powered by Disqus