Sunday, December 18, 2016

Amazon S3 as Image Hosting Service

Create and Configure S3 Bucket

1. Login to AWS Console and create a bucket. In my case images.rubyplus.com.
2.  Add the bucket policy to provide read access to everyone:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/*"]
    }
  ]
}




3. Upload the image to the S3 bucket. You can also access the image using SSL like this: https://s3.amazonaws.com/images.rubyplus.com/no-op-cgol.png

This is the image for my upcoming book TDD in Ruby to be released by Apress in 2017. The SSL is important because when your site uses SSL and some of the links are not https, the browser will show SSL errors in the SSL padlock.

Tip: Use http://jsonlint.com to validate bucket policy and fix issues before configuring the bucket.

Use Amazon CloudFront CDN to Speed Up Image Access

Go to Cloudfront and click Create Distribution, provide the bucket name and accept the default values for other form fields. It will take some time for the changes to take effect.




Once the changes are complete, you can access the images using Cloudfront URL like this:
http://images.rubyplus.com.s3.amazonaws.com/no-op-cgol.png

Using your Own Subdomain to Access Assets

You can create CNAME using the UI provided by your host to map the URL:

http://xyz123.cloudfront.net to http://images.yourdomain.com

I host my Rails app on Linode. I used the dashboard of Linode to map images.rubyplus.com to the cloudfront.net URL by creating a CNAME. Now, we can access the same image without s3.amazonaws.com like this:

https://images.rubyplus.com/no-op-cgol.png





No comments:

Post a Comment