Search code examples
ruby-on-railsasset-pipelinecdnamazon-cloudfront

Serving only image assets from CloudFront with Rails


I recently switched to using CloudFront as a CDN to serve my assets using the simple

config.action_controller.asset_host = "url of your cloudfront distribution" in my config file.

All works well, CF pulls in assets that it doesn't have just fine, serves them just fine, is faster than using the asset pipeline.

However, for a variety of reasons, some of our JS breaks when served from CF and not our own server. So I am looking for a way to use CF just for image (or image/css) assets, and still serve the compiled application.js file directly from our own server.

Any ideas?


Solution

  • Rails allows you to set config.action_controller.asset_host to be a proc. That way you can have as much control as you like over the selection of the asset host. For example:

    config.action_controller.asset_host =  Proc.new { |source|
      if source.ends_with?('.jpg')
        "http://cdn.example.com"
      else
        nil
      end
    }
    

    See the api docs for more details.