Hosting static sites with Amazon S3 and Cloudflare

Last year I wrote about hosting a static site on a vps. This works, but I wouldn’t recommend this approach anymore if you just want to host a simple static site. Managing your own server should be avoided if not necessary. Setting up our static site on Amazon S3 with Cloudflare allows for a cheaper setup with minimal configuration and several benefits provided by Cloudflare.

1. Create an Amazon s3 bucket

Start with creating a bucket on Amazon S3 with the name of your desired domain (examplesite.com) and select a region near you.

2. Upload your site files

You can create your own static site files yourself or you can use a generator like Jekyll or Hugo. When you’ve created the build, upload the contents of your build/public folder to your bucket. In the new Amazon S3 interface, you can upload by dragging and dropping multiple files at once.

3. Set permissons

To use web hosting from your bucket, the items in the bucket should be publicly readable.

Go to your bucket -> permissions tab -> Bucket policy and add the JSON snippet which you can find here (replace the example bucket resource with your bucket name) and save the configuration.

"Resource":["arn:aws:s3:::yourdomain.com/*"

4. Enable webhosting for your bucket

Go to the properties tab -> static website hosting and select the option ‘Use this bucket to host a website’. Set the index and error documents and save your configuration. This will make your site available on the specified endpoint url.

5. Custom domains and SSL with Cloudflare

We can use Cloudflare to use our custom domain and to benefit from it’s ssl and CDN options. Sign up for Cloudflare and go through the ‘add site’ steps. Add your root domain example.com and begin the scan. Depending on your dns provider, Cloudflare will find a bunch of records that already exist. If there are any A records found you can delete those.

What we need is one CNAME record with name: @, content: your bucket site endpoint (example yourbucketname.com.s3-website-eu-west-1.amazonaws.com).

Continue with the setup and select the free plan. The following step is to update your name servers. Go to your domain registrar and change the name servers of your domain to the ones provided by Cloudflare.

This process should result in a ‘pending’ status in your Cloudflare dashboard. Recheck your name servers to check if your domain is active. When your status changes to active, your site should be available on the custom url.

6. SSL

In your Cloudflare dashboard go to crypto –> ssl and set SSL to flexible. Again, it can take some time for the certificate to be issued. We also want to make sure that http traffic is redirected to https. We can do this by adding a page rule in the ‘page rules’ section.

Add a new rule for your domain with http://example.com/* and add the ‘always use https setting’.