Serving a website from Amazon S3

Amazon S3 can be used to serve static content, with all the advantages of scaling and redundancy that you get from Amazon.

There are comprehensive guides to setting up a site in S3 – this is a shortened version to highlight a couple of things.

In my case, I wanted to set up a website to serve some static content at a subdomain of an existing domain which was being managed in Route53.

First, set up a bucket which will hold the website. Note, if you’re planning to use an alias for the domain, then the bucket needs to be named as a subdomain of one that you’re managing in Route53 – eg. static.julianhigman.com.

Next, set up the bucket to be a website, using the properties pane to select “Enable website hosting”. Give it an index filename of index.html (remember, S3 isn’t really serving content the same way as say Apache, which has directory listing built in, so you need to give it a default file to serve at the root URL).

bucket-properties

Now, you need to allow anonymous visitors to read the contents of the bucket. The simplest way is to add a bucket policy. In the Permissions section of the properties, click the “Edit bucket policy” button, and add this (but replacing “static.julianhigman.com” with the name of your bucket):

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::static.julianhigman.com/*"
        }
    ]
}

You should now be able to access your bucket in a web browser, at a URL like http://static.julianhigman.com.s3-website-eu-west-1.amazonaws.com (again, replace static.julianhigman.com with your bucket).

You can create folders in the bucket, and upload content. Folders can have their own index.html file, which will be served by default if the URL path doesn’t include a filename. (And remember, objects in S3 actually all live in the bucket, the hierarchy of folders is being faked by S3 based on the path that you specify for an object when storing or retrieving it).

Finally, set up the alias for your subdomain in Route53 – create a new Record Set for the subdomain, specifying an “A” record, but selecting the “Alias” radio button, and choosing your new S3 website from the Alias Target dropdown (the available S3 websites should appear at the top of the list).

Save the records, and you’re done.

You should now be able serve static content from your S3 bucket.

Leave a Reply

Your email address will not be published.