如何在 Rails 中防止浏览器页面缓存

如何在 Rails 中防止浏览器页面缓存

问题描述:

Ubuntu -> Apache -> Phusion 乘客 -> Rails 2.3

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.

解决这个问题的最佳方法是什么?我应该在 Rails 中解决这个问题吗?阿帕奇?Javascript?

What's the best way to solve this? Should I solve this in Rails? Apache? Javascript?

感谢您的帮助,杰森

唉.这些建议都没有强迫我正在寻找的行为.

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

也许有一个 javascript 答案?我可以让 rails 在评论中写出一个时间戳,然后让 javascript 检查时间是否在五秒内(或任何有效的时间).如果是,那很好,但如果不是,则重新加载页面?

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?

你认为这行得通吗?

感谢您的帮助,

杰森

终于想通了 - http://blog.serendeputy.com/posts/how-to-prevent-browsers-from-caching-a-page-in-rails/application_controller.rb

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

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

Rails 4 及更早版本:

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