How to configure Carrierwave to use multiple CDN CNAME urls

In Rails I can serve assets from a CDN, and set up multiple CNAMES for simultaneous loading.

For example I put config.action_controller.asset_host = "" in config/environments/production.rb, and then my assets are served from

This is great, and dramatically increases page load time.

My app contains a lot of user generated images handled via Carrierwave. I would like to apply the same approach for these images. I've set up the CDN, and in config/initializers/carrierwave.rb I've added the following:

config.asset_host = ""

Now I have two questions:

  1. How do I ensure this CDN is only used in production?
  2. How do I use multiple URLS (e.g. images-0.myapp, images-1.myapp, etc). The %d method does not appear to work in the initializer.


I had the same problem today and came up with this:

# staging

# production

And in your initializer:

# config/initializers/carrierwave.rb
  config.asset_host = proc do |file|
    "#{ENV['S3_CLOUDFRONT_DOMAIN'] % (Zlib.crc32(file.filename) % 4)}"
 config.asset_host = ENV['S3_CLOUDFRONT_DOMAIN']

Note that I'm using ENV variables for my domains and that I have file.filename which corresponds to my mounted column. I didn't have time to find a way to access the mountable column through a helper so I'll have to come back to that, for now it works.

This will handle both multiple CDN endpoints and a single endpoint for staging or development. Make sure that the protocol or at least "//" is provided for your endpoints otherwise Carrierwave thinks it's a folder an ends up with /images/

Hope that works for you too.

Also, I'm using Carrierwave 0.9.0

Johnkoht's answer got me looking at the carrierwave reference docs. They suggest

CarrierWave.configure do |config|
  config.asset_host = proc do |file|
  identifier = # some logic (note: I used "images-#{rand(3)}
  "http #{identifier}"

I combined this with a dedicated initializer for carrierwave production and got it working

Need Your Help

Xampp - localhost not working

apache xampp localhost

Although apache seems as "working" on xampp control panel,I can't reach the localhost or . I changed 80 port to 81 but not solved.

Anchor tags functional but smooth scrolling won't work; page acts like javascript isn't there

javascript html smooth-scrolling

I'm writing a single-page website in HTML. I want to use javascript for smooth scrolling between anchor tags. I've looked at half a dozen demos online, and copy/pasted relevant code directly into my