Search code examples
ruby-on-railsamazon-s3paperclipamazon-cloudfront

Paperclip s3_host_alias not working


I'm trying use the Cloudfront CNAME in s3_host_alias but isn't working.

config/s3_config.yml

development:
  url: ":s3_host_alias"
  s3_host_alias: dev-cdn.mysite.com
production:
  url: ":s3_host_alias"
  s3_host_alias: cdn.mysite.com

models/profile.rb

def self.s3_config
    @@s3_config ||= YAML.load(ERB.new(File.read("#{Rails.root}/config/s3_config.yml")).result)[Rails.env]
end

has_attached_file :avatar, :storage => :s3, :s3_credentials => "#{Rails.root}/config/s3.yml", :url => self.s3_config['url'], :s3_host_alias => self.s3_config['s3_host_alias'], :styles => { :medium => "300x300>", :circle => "130x130#", :thumb => "50x50>" }, :default_url => "avatar/missing.jpg", :path => ":class/:id/:attachment/:style/:hash.:extension", :url => ":class/:id/:attachment/:style/:hash.:extension", :hash_secret => "***"

Tried the code with CNAME direct in model and don't work too.

has_attached_file :avatar, :storage => :s3, :s3_credentials => "#{Rails.root}/config/s3.yml", :url => ":s3_host_alias", :s3_host_alias => "dev-cdn.mysite.com", :styles => { :medium => "300x300>", :circle => "130x130#", :thumb => "50x50>" }, :default_url => "avatar/missing.jpg", :path => ":class/:id/:attachment/:style/:hash.:extension", :url => ":class/:id/:attachment/:style/:hash.:extension", :hash_secret => "***"

The website keeps using the full s3 bucket url...


Solution

  • I ran into this problem as well: neither the :s3_host_alias nor :url would read from config/s3.yml. I was able to make it work by putting both fields in the model but keeping s3.yml for the bucket, access_key_id, and secret.

    A quick workaround might look something like this:

    if Rails.env.production?
        host_alias = "cdn.mysite.com"
    elsif Rails.env.development?
        host_alias = "dev-cdn.mysite.com"
    end 
    

    then

    has_attached_file   :avatar, 
                        ...
                        :url            => ":s3_alias_url",
                        :s3_host_alias  => host_alias,
                        :credentials => ...