Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding amazon urls when using S3, Rails and Paperclip

I have just set up file uploads to Amazon S3 using Rails 3 and Paperclip. All this works amazingly well and is up and running. There is just one small detail that I would like to sort out. At the moment, the urls are the amazon urls (ie start http://s3.amazonaws.com) and I would like them to begin with my domain.

I have already added the neccesary CNAME records to my DNS and they are working fine so I can access the files via a subdomain of my domain. The problem is just that the URLs generated by paperclip start with the amazon domain. Is there an easy way to change the paperclip config to get round this?

Cheers

like image 618
Addsy Avatar asked Sep 25 '10 22:09

Addsy


2 Answers

Take a look at Paperclip::Storage::S3.

like image 113
yfeldblum Avatar answered Nov 10 '22 19:11

yfeldblum


Here's everything you need to hide the Amazon urls of your S3 assets:

  1. Name your S3 bucket after the domain alias you want to use. So if you want to access your assets at http://assets.mysite.com/path/to/image.png then you should name your S3 bucket: assets.mysite.com

  2. Add a CNAME to your DNS records so that assets.mysite.com is an alias of assets.mysite.com.s3.amazonaws.com (Don't include '.mysite.com' in 'name' field of the DNS record.)

  3. Setup paperclip to use your new domain alias insetad of the default S3 path:

     has_attached_file :my_file,
         ...
         :url => ':s3_alias_url'
         :s3_host_alias => 'assets.mysite.com',
         ...
    

I usually have different buckets for development, staging and production and I only use the domain alias for the prod bucket. So to ensure it works in each environment, my :url setting often like this:

:url => (ENV['USE_S3_ALIAS'] == 'TRUE' ? ':s3_alias_url' : ':s3_domain_url')
like image 24
Ryan Epp Avatar answered Nov 10 '22 19:11

Ryan Epp