Set Cache-Control Header
Asked Answered
T

1

7

Let's say that I have a public/marketing controller and I want to set the response header with Cache-Control: max-age=180, public, must-revalidate

I can't find documentation for setting that at the controller level?

Triboluminescence answered 23/4, 2018 at 19:35 Comment(0)
E
9

There are a few options that come into mind.

Option 1:

Using expires_in helpers from ActionController::ConditionalGet. These are included in both ActionController::Base and ActionController::API, as far as I remember (http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html).

def some_action
  @some_user_for_view = User.first
  expires_in 3.hours, public: true
end

Option 2:

Setting headers manually with setting #headers on the response object. directly. (http://edgeguides.rubyonrails.org/action_controller_overview.html#the-response-object)

before_action :set_headers

def set_headers
  response.headers["Expires"]='Mon, 01 Jan 2000 00:00:00 GMT'
  response.headers["Pragma"]='no-cache'
  response.headers["Cache-Control"]="no-cache"
  response.headers["Last-Modified"]=Time.now.strftime("%a, %d %b %Y %T %Z")
end

The first option would be the most 'railsy', however using the second option yields a few more options in terms of customization of headers.

Enjoy answered 23/4, 2018 at 19:55 Comment(1)
Option 2 gave me a 502 error with Nginx. It seems unhappy about the format for the Expires and Last-Modified headers, for now I just removed them and the error is gone.Reckless

© 2022 - 2024 — McMap. All rights reserved.