Search code examples
ruby-on-railsamazon-s3asset-pipelinecarrierwaveamazon-cloudfront

CarrierWave With Cloudfront Generating wrong URL


Hello I am using Cloudfront with CarrierWave and S3. For some reason in my app I am getting very strange URLs for my cloudfront path when using image_tag and I don't know where I am going wrong. Here is my carrierwave config file

CarrierWave.configure do |config|
config.fog_provider = 'fog/aws'                        # required

config.fog_credentials = {
provider:              'AWS',                        # required
aws_access_key_id:     'accesskey',                        #   required
aws_secret_access_key: 'secretaccess key',                          # required
region:                'us-east-1',                  # optional, defaults to 'us-east-1'
}

config.fog_directory  = 'bwautosales'                          # required
# config.asset_host = 'randomletters.cloudfront.net'
config.asset_host = 'randomletters.cloudfront.net'
config.fog_public = true
config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" } #  optional, defaults to {}
 end

and my production.rb file I have

 config.action_controller.asset_host = 'randomletters.cloudfront.net'

but in my view when I do something like

 <%= link_to image_tag(car.images[0], class: "img-responsive right-block", id: index), car %>

I get this -

src = https://randomletters.cloudfront.net/images/randomletters.cloudfront.net/uploads/car/images/28/car.png"

I'm sure this is an easy fix but don't know where I'm going wrong. Any help would be appreciated!

Image Uploader `

class ImageUploader < CarrierWave::Uploader::Base

include CarrierWave::MiniMagick

storage :fog

def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

def extension_whitelist
 %w(jpg jpeg gif png)
end

end

`


Solution

  • In your Carrierwave initializer change the line,
    config.asset_host = 'randomletters.cloudfront.net' to config.asset_host = 'http://randomletters.cloudfront.net' to get the required cloudfront URL you needed.

    You can also remove the line, config.action_controller.asset_host = 'randomletters.cloudfront.net' from Production.rb as the carrierwave itself fetches from the cloud-front url.

    CarrierWave.configure do |config|
        config.fog_provider = 'fog/aws'                        
    
        config.fog_credentials = {
        --------------
        --------------
        }
    
        config.fog_directory  = 'bwautosales'                          
        config.asset_host = 'http://randomletters.cloudfront.net' # please check the change in this line.
        config.fog_public = true
        config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" } #  optional, defaults to {}
    end