Rails 未提供 Cloudfront 资产

Rails Cloudfront assets not served

我为 Rails 使用 Heroku 设置了 Cloudfront,一开始它运行良好。我最近几天注意到 cloudfront.net 不再提供资产。

Production.rb

Rails.application.configure do
  config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.action_controller.asset_host = 'http://d2t6o5tnu5etuf.cloudfront.net'
  config.serve_static_files = true
  config.assets.js_compressor = :uglifier
  config.assets.css_compressor = :sass
  config.assets.compile = true
  config.assets.digest = true
  config.assets.version = '1.0'
  config.log_level = :info
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
  config.log_formatter = ::Logger::Formatter.new
  config.active_record.dump_schema_after_migration = false
end

我可以访问云端地址下的所有资产,在 chrome 中我可以看到应用程序-5deb6995ce9b984d469b27c58cc92a095d19cd13e0acd622ffe426c41826e055.js 从云端服务器获得服务。但是页面上的所有静态图像,例如/assets/shop/banners/2.jpg 没有。

好像和预编译有关,因为它没有查找文件的指纹版本,或者?

在我的 gem 文件中包含以下内容:

group :production, :staging do
      gem 'rails_12factor'
      gem 'pg'
 end

正如 tegon 指出的那样,需要 image_tag 或 image_url 来为来自云端的资产提供服务。我的代码中有通常的 "img src" 引用,但无法识别。

将 img src 更改为 image_tag 或 image_url,它正在运行。谢谢!

这是一个使用 CloudFront 的示例 Rails 5.2 应用程序:https://github.com/nzoschke/edgecors

除了 asset_host 之外,您还应该为您的资产配置 Cache-Control header。这就是 CloudFront 几乎永远缓存不可变的 application-5deb6995ce9b984d469b27c58cc92a095d19cd13e0acd622ffe426c41826e055.js 命名资产。

Rails.application.configure do
  config.action_controller.asset_host = "https://d372g5jsa84e2.cloudfront.net"
  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=31536000'
  }
end

如上评论,使用资产管道 url 助手。这是 SCC font-url 助手的示例:

@font-face {
  font-family: 'Inconsolata';
  src: font-url('Inconsolata-Regular.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: "Inconsolata";
}