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 = "http://assets-%d.myappp.com" in config/environments/production.rb, and then my assets are served from

http://assets-0.myapp.com
http://assets-1.myapp.com
http://assets-2.myapp.com

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 = "http://images.myapp.com"

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.

Answers


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

# staging
ENV['S3_CLOUDFRONT_DOMAIN'] = "//s3.amazonaws.com/bucket"

# production
ENV['S3_CLOUDFRONT_DOMAIN'] = "//assets%d.domain.com"

And in your initializer:

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

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/s3.amazonaws.com/site/path/to/file.jpg

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}.cdn.rackspacecloud.com"
  end
end

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 127.0.0.1 . 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