Rails Cloudfront assets not served

2019-09-03 12:41发布

问题:

I set-up Cloudfront with Heroku for Rails and in the beginning it worked fine. I noticed in the last days that the assets are not served from cloudfront.net any longer.

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

I can reach all my assets under the cloudfront adress and in chrome i can see that application-5deb6995ce9b984d469b27c58cc92a095d19cd13e0acd622ffe426c41826e055.js gets served from cloudfront server. However all static images on the page e.g. /assets/shop/banners/2.jpg do not.

It seems to have to do with the precompiling, since it does not look for the fingerprint version of the file, or?

In my gem-file I have the following included:

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

回答1:

As tegon poined out, image_tag is or image_url is needed to serve the assets from cloudfront. I had the usual "img src" reference in my code, which will not be recognized.

Changed img src to image_tag or image_url and it was working. Thanks!



回答2:

Here's an example Rails 5.2 app using CloudFront.: https://github.com/nzoschke/edgecors

In addition to the asset_host you should configure a Cache-Control header for your assets. This is so CloudFront caches the immutable application-5deb6995ce9b984d469b27c58cc92a095d19cd13e0acd622ffe426c41826e055.js named assets virtually forever.

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

As comments above, use the asset pipeline url helpers. Here's an example of the SCC font-url helper:

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

body {
  font-family: "Inconsolata";
}