157

Ubuntu → Apache → Phusion Passenger → Rails 2.3.

The main part of my site reacts to your clicks. So, if you click on a link, it will send you on to the destination, and instantly regenerate your page.

But, if you hit the back button, you don't see the new page. Unfortunately, it's not showing up without a manual refresh; it appears the browser is caching it. I want to make sure the browser does not cache the page.

Separately, I do want to set far-future expiration dates for all my static assets.

What's the best way to solve this? Should I solve this in Ruby on Rails? Apache? JavaScript?


Alas. Neither of these suggestions forced the behavior I'm looking for.

Maybe there's a JavaScript answer? I could have Ruby on Rails write out a timestamp in a comment, and then have the JavaScript code check to see if the times are within five seconds (or whatever works). If yes, then fine, but if no, then reload the page?

Do you think this would work?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason Butler
  • 5,619
  • 3
  • 22
  • 18

6 Answers6

346

I finally figured this out - http://blog.serendeputy.com/posts/how-to-prevent-browsers-from-caching-a-page-in-rails/ in application_controller.rb.

After Ruby on Rails 5:

class ApplicationController < ActionController::Base

  before_action :set_cache_headers

  private

  def set_cache_headers
    response.headers["Cache-Control"] = "no-cache, no-store"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Mon, 01 Jan 1990 00:00:00 GMT"
  end
end

Ruby on Rails 4 and older versions:

class ApplicationController < ActionController::Base

  before_filter :set_cache_headers

  private

  def set_cache_headers
    response.headers["Cache-Control"] = "no-cache, no-store"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Mon, 01 Jan 1990 00:00:00 GMT"
  end
end
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason Butler
  • 5,619
  • 3
  • 22
  • 18
  • 4
    Should this be wrapped in a "if request.xhr?" so it only gets set on ajax refreshes but the normal pages do not? – CafeHey Aug 24 '12 at 12:04
  • @Smickie I've done exactly that. I only needed my Ajax requests to not be cached. Otherwise this answer is perfect! – Ashish Tonse Mar 07 '13 at 20:40
  • I recommend wrapping in `if request.xhr` to only bust the cache for ajax requests like @Smickie mentioned. If you stop all caching for all requests, good luck scaling down the road. – Archonic Sep 24 '13 at 15:53
  • 3
    You only really need `Cache-Control: no-store` as long as the browser is compliant with HTTP 1.1. [Section 14.9.2 What May be Stored by Caches](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2) – gaqzi Oct 07 '14 at 02:05
  • 34
    Jan 1, 1990, was a Monday! – Jan Hettich Oct 29 '14 at 17:55
  • 2
    Its not working for me I have add the same code in application_controller.rb and after logout I am able to see the last page by back button. Please guide me where I am wrong? – Thorin Jan 21 '15 at 13:27
  • 1
    Will this also NOT cache JS and CSS in rails app ? Will JS and CSS be loaded from server for each request ? – furiabhavesh Feb 13 '15 at 12:14
  • Isn't it completely disabling caching for app? Because it will be located in application_controller.rb? – msdundar Mar 20 '15 at 23:28
  • This preventing caching for FF and Chrome, but not in IE 11. Is there anything more to do for IE?? – Sambit May 14 '15 at 13:00
  • The link is broken (DNS domain expiration?): *"Hmm. We’re having trouble finding that site. We can’t connect to the server at blog.serendeputy.com."* – Peter Mortensen May 10 '22 at 13:48
16

Use:

expires_now()

expires_now()

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sacre
  • 177
  • 1
  • 2
  • 5
    `expires_now` only sends the `no-cache` header. Depending on the browser this might not be enough. (For example Firefox wants a `no-store` for non-HTTPS connections: https://developer.mozilla.org/en/docs/Using_Firefox_1.5_caching ) – Daniel Rikowski Dec 03 '12 at 10:21
  • 1
    Agreed, this is not a valid solution, tested with Rails 5.2 and Chrome 77. `no-store` is also needed. – Andrew Smith Oct 25 '19 at 04:33
3

I have used this line with some success in the controller. It works in Safari and Internet Explorer, but I haven't seen it work with Firefox.

response.headers["Expires"] = "#{1.year.ago}"

For your second point, if you use the Ruby on Rails helper methods like

stylesheet_link_tag

and leave the default settings on your web server, the assets are typically cached pretty well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
erik
  • 6,406
  • 3
  • 36
  • 36
1

Point of note: You can't conditionally clear the cache (like if a before_filter only calls reset_cache if the user's already been there). You need to unconditionally clear the cache, because the browser won't make a new request just to see if this time it needs to reload, even though it didn't need to last time.

Example:

before_filter :reset_cache, if: :user_completed_demographics?

won't work to prevent users from coming back after they've been there, since the browser uses the original cache headers on the Back button.

before_filter :reset_cache

will work, however (after refreshing the page and clearing the cache from before you added this, obviously), since, on the first request, the browser will get the no-cache, no-store, ... and apply it to future page loads.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

The cleaner way would be to write Rack middleware, which changes the Cache-Control header based on some logic (for example, only for application/xml mime-type).

Or, for an uglier, but still working approach, one could change the ActionDispatch::Response::DEFAULT_CACHE_CONTROL constant to 'no-cache'.

Of course, if the controller and/or action granularity is required, then it's better to do this in the controller.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roman
  • 13,100
  • 2
  • 47
  • 63
1

no_cache_control Gem.

If you need to do this for all responses, e.g., to pass a penetration test (Burp Suite, Detectify, etc.), you can install this Gem on Ruby on Rails 4+ in order to add the following headers to all responses:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: -1

It works like a charm and is really the right way to go for secure, HTTPS web applications that require authentication to do anything.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245