views:

3028

answers:

5

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 Rails? Apache? Javascript?

Thanks for all your help, Jason

+1  A: 

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 the rails helper methods like

stylesheet_link_tag

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

erik
+4  A: 

Unfortunately, you cannot guarantee that a browser will not cache a page. It's simply not possible.

However, you can tell browsers that implement caching standards not to cache a page. You do this with http headers like:

Pragma: no-cache

and

Cache-Control: no-cache

So in rails, you would use:

response.headers["Pragma"] = "no-cache"
response.headers["Cache-Control"] = "no-cache"

I recommend you include both, just in case. Either should work for most browsers.

Randolpho
Thanks. I'll try this today.
Jason Butler
let me know how it goes
Randolpho
A: 

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

Maybe there's a javascript answer? I could have rails write out a timestamp in a comment, then have the javascript 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?

Thanks for all your help,

Jason

Jason Butler
+4  A: 

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

..in application_controller.rb..

  before_filter :set_cache_buster

  def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end
Jason Butler
Thanks ...saved me a ton of time!
mikeymo