加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 设置除某些文件之外的public_file_server.head

发布时间:2020-12-17 03:10:55 所属栏目:百科 来源:网络整理
导读:我在production.rb中使用它: config.public_file_server.headers = { 'Cache-Control' = 'public,s-maxage=31536000,maxage=31536000','Expires' = "#{1.year.from_now.to_formatted_s(:rfc822)}"} 我通过cdn.mydomain.com使用公共文件,该文件是从www.mydom
我在production.rb中使用它:

config.public_file_server.headers = {
  'Cache-Control' => 'public,s-maxage=31536000,maxage=31536000','Expires'       => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}

我通过cdn.mydomain.com使用公共文件,该文件是从www.mydomain.com读取的,它从www.mydomain.com复制缓存控制,我使用public_file_server.headers设置.

问题是我希望/ public中的某些文件没有那些缓存控制,例如我的service-worker.js

有没有办法只为/ public中的一个文件夹设置这些缓存控制?

另一个解决方案是删除这个public_file_server.headers配置,并在cdn级别设置缓存控制(我使用cdn.mydomain.com/publicfile),并保持www.mydomain.com/serviceworker没有缓存控制,用于服务工人.

但也许有机会在Rails级别配置它?

解决方法

我有完全相同的问题:使用CDN(Cloudfront)使用Rails构建PWA.对于我想要使用远期未来的缓存头的资产,但ServiceWorker需要缓存控制:无缓存.

由于CloudFront不允许自行添加或更改标头,因此我需要在应用级别上提供解决方案.经过一些研究后,我在blogpost中找到了一个解决方案.想法是通过public_file_server.headers设置头文件,并添加一个中间件来为ServiceWorker文件更改它.

这是我使用的代码:

production.rb:

config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.public_file_server.headers = {
  'Cache-Control' => 'public,max-age=15552000','Expires' => 1.year.from_now.to_formatted_s(:rfc822)
}

if ENV['RAILS_SERVE_STATIC_FILES'].present?
  config.middleware.insert_before ActionDispatch::Static,ServiceWorkerManager,['sw.js']
end

应用程序/中间件/ service_worker_manager.rb:

# Taken from https://codeburst.io/service-workers-rails-middleware-841d0194144d
#
class ServiceWorkerManager
  # We’ll pass 'service_workers' when we register this middleware.
  def initialize(app,service_workers)
    @app = app
    @service_workers = service_workers
  end

  def call(env)
    # Let the next middleware classes & app do their thing first…
    status,headers,response = @app.call(env)
    dont_cache = @service_workers.any? { |worker_name| env['REQUEST_PATH'].include?(worker_name) }

    # …and modify the response if a service worker was fetched.
    if dont_cache
      headers['Cache-Control'] = 'no-cache'
      headers.except!('Expires')
    end

    [status,response]
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读