本文介绍了如何防止 Rails 中的浏览器页面缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ubuntu -> Apache -> Phusion Passenger -> 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?

感谢您的所有帮助,杰森

Thanks for all your help,Jason

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

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

这篇关于如何防止 Rails 中的浏览器页面缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:47
查看更多