设置 Rails 资源的缓存控制

Can*_*yer 5 ruby ruby-on-rails ruby-on-rails-5

我的 application_controller.rb 中有以下代码

before_action :set_cache_headers

def set_cache_headers
  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
Run Code Online (Sandbox Code Playgroud)

这也会导致我的资产在每次请求时重新加载。在 Rails 中,如何在每个请求上重新加载 HTML,而不是资源?

我想要这样的东西(除了 Rails 内):

<filesMatch ".(css|jpg|jpeg|png|gif|js|ico|JPG|woff)$">
    Header set Cache-Control "max-age=2592000, public"
</filesMatch>
Run Code Online (Sandbox Code Playgroud)

G_8*_*_89 4

由于Rails for Prod env中的action_controller缓存默认为ON,因此还设置了Control-Cache。但是 ApplicationController 中的过滤器会覆盖它,从而禁用整个缓存。尝试将此行粘贴到您的 config/initializers/assets.rb 文件中:

Rails.application.config.public_file_server.headers = {
  'Cache-Control' => "public, max-age=#{some_number}"
}
Run Code Online (Sandbox Code Playgroud)

因为some_number您需要一个以秒为单位的值,例如30.days.to_i