Skip to content

jasonfb/cdn-image-tag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This gem is for Rails 8 to allow you to serve images + Active Storage assets from a CDN, via Active Storage proxy.

In Active storage proxy mode, assets are stored on S3 but served from the Rails app.

To speed performance and reduce load on the Rails app, you use a CDN that points to the Rails app itself (not S3)

Go to your CDN and create a distribution with an origin that points back to the domain of your Rails app.

AWS Cloudfront

For AWS Cloudfront: On the Origin edit screen, set these:

  • Protocol: "HTTPS only"
  • Minimum Origin SSL protocol: "TLSv1.2"

Then go to the Behaviors tab on the distribution, select the default behavior ("0"), and check these settings:

  • Viewer protocol policy: Https only
  • Allowed HTTP methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
  • Restrict viewer access: No
  • Cache policy: CachingOptimized
  • Origin request policy: AllViewerExceptHostHeader

INSTALL

  • Setup S3 (see Active Storage docs + example below)
  • Set Cloudfront or another CDN (see above)
  • Set an ENV variable CDN_TO_SELF to the CDN distribution domain; (sub)domain only (not including protocol)
  • Include this gem in your gemfile
  • Wherever you would use image_tag, instead use cdn_image_tag

// production.rb

config.active_storage.service = :amazon
config.action_mailer.asset_host = "https://#{ENV['CDN_TO_SELF']}"
config.active_storage.cdn_host = ENV['CDN_TO_SELF']
config.active_storage.routes_host = ENV["CDN_TO_SELF"]
config.active_storage.resolve_model_to_route = :rails_storage_proxy

// DO NOT SET config.action_controller.default_url_options

// storage.yml

amazon:
    service: S3
    access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
    secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
    region: <%= ENV['AWS_REGION'] %>
    bucket: myapp-<%= Rails.env %>

(I like my bucket names to be myapp-production and myapp-devlepment to match the Rails env, but you can modify this as needed)

Verify:

  • Deploy your app, look at an image, right-click to "Open image in new tab", and confirm that the CDN is used instead of the Rails app domain.
  • You can swap the CDN domain for your Rails app domain and get the same image
  • The images from the asset pipeline should have the pipeline's thumbprint
  • Images served from Active storage have URLs like /rails/active_storage/representations/proxy/

About

For Rails 8, a gem that adds cdn_image_tag helper for serving assets from a CDN

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages