Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cache-Control Header

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?

like image 699
Tom Rossi Avatar asked Apr 23 '18 19:04

Tom Rossi


1 Answers

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.

like image 195
Frederik Spang Avatar answered Oct 07 '22 18:10

Frederik Spang