Setting Up CloudFront With S3

Yesterday I decided to setup CloudFront for Computoser. I store all the generated tracks in AWS S3, and every time a track is played or downloaded, I was making a request to S3. Not that the traffic is that much, but still it sounded like a good idea to use a CDN (CloudFront) – it would save a little bit of money (not that the current bill is any big) and it would make download faster accross the globe. To be honest, I didn’t do it for any of these – I was just curious how would a CloutFront setup work.

There is enough documentation on “How to setup CloudFront with S3″, and besides, the UI in the AWS console is pretty straightforward – you create a “distribution”, in “Origin” you specify your S3 bucket, and that’s it. Of course, you can use your own server as origin server, if you don’t store the content in S3.

Then you wait for around 10-15 minutes, and things should work – i.e. when you access, it should be opened. But for me it wasn’t – the response was “Access denied”. Which meant the bucket policy had to be changed (as described here):

  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]

Then the application had to be configured to use CloudFront. This can be done in two ways:

  • In the view – in your pages you can set the root of the CloudFront, and make all references to CDN-available resources absolute
  • In a controller (or anything back-end) – if it is not about static resources, but (as in my case), files that are generated and stored by the software, then configure the path, and instead of fetching from S3, redirect to the CloudFrount URL.

Both approaches can be useful and easy to roll-out. For the former to work out-of-the-box, you’d need some pre-existing handling mechanism for static resources (e.g. a ${staticRoot} prefix, or a custom tag. It is generally a good idea to have a good static resources setup, regardless of whether you use a CDN or not.

But for bigger systems, a CDN is useful and apparently – easy to setup.