Ask A Question

Notifications

You’re not receiving notifications from this thread.

How can I setup Cloudfront CDN for Rails App ?!

Anh Vy Nguyen Vuong asked in Rails

It's good to have CDN enabled to speed up rails app but how can I do that with Cloudfront ?!

Reply

I've been meaning to do a screencast on this at some point.

This tutorial is pretty good for walking through all the steps needed to setup Cloudfront: https://www.happybearsoftware.com/use-cloudfront-and-the-rails-asset-pipeline-to-speed-up-your-app.html

For the most part it's super easy with Rails since all you need to really change is the asset_host config option. Rails will still serve up assets so that Cloudfront will always get the latest copy. It works really well.

Reply

Wow, thanks.
I tried and it's really easy to setup. But I have some error with this: "Access to Font .. has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource..."

Do you have any idea to resovle this ?!

Reply

Yeah, good ol' CORS. You can add rack-cors to your gemfile and create this initializer to take care of it:

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '/assets/*',
      headers: :any,
      methods: [:get]
  end
end

Basically what's happening is you're including now your stylesheets from a different domain (cloudfront's domain, not yours anymore) and the browser won't allow it unless you tell it that it's okay.

Reply

I added rack-cors as your recommendation but didn't work. :(

FYI: This app using Rails 4.
And I also found this article: https://ricostacruz.com/til/rails-and-cloudfront He mentioned all step there

Reply

That's where I got the snippet from actually. Forgot to paste the link. :)

Reply

I sovled it by combining many methods such as:

  • Add custom header to Cloudfront Origin (Done in dashboard)
  • Add Nginx Mimes types and add header forward there (Done in server block of Nginx config file)
  • Add rack-cors and put your snippet it in application.rb .
  • Enable serving static assets config.serve_static_assets = true
  • Clear cloudfront cache by creating Invalidation (Done in dashboard)

Not sure which one make impact, but it's urgent so I'll try one by one next times. Btw. thanks for your support Chris !

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.