Your Static Website In AWS

If you have a static website, that doesn’t require user login, dynamic content, or a running app etc. simplest way is to serve it by using an S3 bucket + Cloudfront. Here’s how you can do it:

  1. Create an S3 bucket. Block public access. Disable web hosting. Do not add any policies yet. Just create the bucket, with any name, in any region.

  2. Upload the built version of your website (dist folder) into your S3 bucket.

  3. Navigate to Certificate Manager, select us-east-1 region and request a new certificate that includes your main domain (example.com) as well as wildcard of your domain (*.example.com). Select DNS validation as preferred method and keep the records - you will need them in a bit.

  4. Create a Cloudfront distribution with following options:

    • Origin: S3 REST endpoint with Origin Access Control (OAC) enabled
    • Behavior: Redirect HTTP to HTTPS, GET/HEAD only and CachingOptimized
    • Error pages: 403 and 404 → you can point them both to /index.html with 200 response. If you have custom pages, you can also point them instead.
    • Alternate domain names: add both values from the certificate you created at certificate manager (e.g. example.com, *.example.com)
    • SSL: the combined ACM certificate with TLS policy TLSv1.2_2021
    • Default root object: index.html or however you name the main page.
    • No WAF, no logging, no mTLS
  5. Enable Cloudfront over S3: When you create OAC at Cloudfront / Origin page, it generates an OAC Policy. Copy the policy created, and paste it into permissions policy of your S3 bucket.

  6. Wherever you registered your domain (Route 53, godaddy, namecheap etc) add CNAME records to register your Cloudfront distribution: key should be @ and the value should be your cloudfront distribution, similar to vnsdvgdfg5t.cloudfront.net. Feel free to add another one with www as key and cloudfront distribution as value, if you want your website accessible with www at the beginning.

If you want to automate the process of adding new files to your website, you can use Github Actions. It’s super easy to set up and very efficient to update your S3 bucket, then your website.

Many details are outdated in recent articles about hosting your website with S3 and Cloudfront. A few details you have to know:

  • Your S3 bucket doesn’t have to have the same name as your domain,
  • You don’t need public access to your S3 bucket or static web hosting enabled,
  • You don’t have to register your domain at Route53,
  • You don’t have to pick a paid service at Cloudfront,
  • You don’t need WAF or Global Accelerator.

P.S: Github pages can be a good alternative, but I don’t appreciate the limitations and the condition to keep your source repository public in order to host your website in GH pages. I prefer to take a little extra step and keep my project files private. However if you don’t have similar concerns, GH pages can be a much easier and better alternative as well.