⚠️ Read this before you follow the Let's Encrypt steps below. They work, but you re-do them every 90 days, and one day you forget. Mine silently expired and served a broken certificate for weeks. 👉 Use ACM instead: validate once, auto-renew forever

Also see: Why There's a Trailing Slash, S3 access problem

Also see: The AWS setup behind this site

This guide provides detailed instructions on setting up a static website using AWS S3, Route 53, and CloudFront, including enabling HTTPS. Involving several key steps, including S3 bucket setup, domain configuration, and implementing secure HTTPS connections.

S3 Hosting Only

If you're ok with that long long url, stop here.

Domain CNAME to S3

If you don't want an unattractive domain name:

Purchase a domain, set a CNAME record pointing to your S3 bucket's website endpoint

aws CNAME [your s3 endpoint]

If you're ok with adding CNAME to spec s3 endpoint everytime, stop here.

Using Route 53 (no HTTPS)

  1. Create a hosted zone in Route 53 name: aws.domain.com

  2. Add an A Record, set as an alias pointing to the S3 website endpoint. You can select this from options AWS provides

    A - Routes traffic to an IPv4 address and some AWS resources

  3. Wherever domain.com's DNS is hosted (your registrar's DNS settings, or a DNS provider such as Cloudflare if you moved it there), add four NS records named aws that point aws.domain.com to the AWS name servers of the zone from step 1. Add records; do not change domain.com's own name servers:

aws NS ns-2048.awsdns-64.com
aws NS ns-2049.awsdns-65.net
aws NS ns-2051.awsdns-67.co.uk
aws NS ns-2050.awsdns-66.org

If no HTTPS is ok for you. Skip next.

CloudFront grands you HTTPS

Step 1: AWS CloudFront

Step 2: Obtaining Let's Encrypt Certificate (optional)

ACM validation process is time-comsuming and need my domain email. I just choose lets encrypt to accelerate the process.

When adding SSL, there's a step to pause and add a TXT Record in Route531

brew install certbot
sudo certbot certonly --manual --preferred-challenges=dns -d aws.domain.com
# Some guidelines to review, keep saying y
# TXT record Please deploy a DNS TXT record under the name:
**_acme-challenge**.aws.domain.com.
with the following value:
zA7PnMP...bAf9oUUdQT0

Upon success, it tells you files are generated in /etc/letsencrypt/live/aws.domain.com/. You'll need two files from this folder:

Step 3: Import Certificate to ACM

Step 4: CloudFront

  1. Choose the Certificate you just created
  2. Alternate domain name (CNAME): Add the domain you want protected by HTTPS2

Step 5: Route 53

Change your original domain.com A record from pointing to S3 resource to pointing to CloudFront

Certificates are valid for 90 days, so repeat steps 2 to 4 after expiration

CloudFront grands you HTTPS (another way)

If you don't want your S3 website endpoint to be directly accessible (http://your-bucket.s3-website-us-east-1.amazonaws.com/), even if you've already configured your own domain name with Route 53 and set up CloudFront, and you only want to access S3 through CloudFront while blocking all other access:

Step 1: Create OAC

In CloudFront > Origin access > Create Control Setting, simply create it. This step is straightforward.

Step 2: Add a Cloudfront Function

  1. You need to create a new CloudFront Function. With OAC (Origin Access Control), accessing domain.com/ does not load the page unless it becomes domain.com/index.html, and domain.com/page without the slash is not redirected to domain.com/page/: S3 answers 403. This function handles both.

    function handler(event) {
      var uri = event.request.uri;
      if (uri.endsWith('/')) {                       // /page/ → /page/index.html
        event.request.uri = uri + 'index.html';
        return event.request;
      }
      var last = uri.substring(uri.lastIndexOf('/') + 1);
      if (last.indexOf('.') === -1) {                // /page  → 301 to /page/
        return {
          statusCode: 301,
          statusDescription: 'Moved Permanently',
          headers: { location: { value: uri + '/' } }
        };
      }
      return event.request;                          // /fav.svg and other files as they are
    }
  2. Then go to Distribution > Behaviors tab > Edit > Function associations > Viewer request > CloudFront Function > Select Function ARN / Name to complete the binding. This means that now a request ending in / is rewritten before it reaches S3 (/page/ becomes /page/index.html), and a request with no slash and no extension gets a 301 to the same path plus /.

You will not see the first change: the address bar still shows /page/. The 301 you do see, because the browser follows it to /page/.

Step 3: Associate OAC to your Distribution Origin

  1. Go editing a Distribution > Origins Tab > Select Origin > Edit, for the Origin domain field, AWS suggests "For Origin domain, choose your S3 target. It suggests using the website endpoint." Ignore this suggestion and keep the simple S3 endpoint, as this allows you to set up Origin access in the next step

    When using S3 with CloudFront and OAC, the bucket needs to use the S3 object access endpoint rather than the static website endpoint. This is why you need step 2 to create a middleware-like function to handle this.

  2. For Origin access, select Origin access control settings (recommended) and associate it with the OAC you added in step 1.

Step 4: Rewrite Bucket Policy at Least Privilege

  1. Go back to S3 and rewrite the Bucket policy. Remove the potentially risky "allow all" policy and replace it with a policy that denies all access by default, only allowing access from a specific Distribution. This creates a whitelist.

    {
        "Version": "2008-10-17",
        "Id": "PolicyForCloudFrontPrivateContent",
        "Statement": [
            {
                "Sid": "AllowCloudFrontServicePrincipal",
                "Effect": "Allow",
                "Principal": {
                    "Service": "cloudfront.amazonaws.com"
                },
                "Action": "s3:GetObject",
                "Resource": "arn:aws:s3:::<your-bucket>/*",
                "Condition": {
                    "StringEquals": {
                        "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<distribution id>"
                    }
                }
            }
        ]
    }

Remember: if you don't set up the Origin Access Control (OAC) for your bucket policy, even if you whitelist your CloudFront distribution, it will be meaningless. So, always remember to do step 1.

This configuration ensures that your S3 content can only be accessed through the specified CloudFront Distribution, providing enhanced security and access control.

Distribution Invalidation

What If: Your S3 bucket has been updated, but the changes are not being reflected when accessed through your domain.

To resolve this, you need to create an invalidation in CloudFront and specify that all files should be invalidated so that they are re-fetched.

read: AWS cloudfront not updating on update of files in S3

Some Thoughts

Thought 1

Regarding AWS resource configuration, you're often told to set the bucket name equal to the domain name, same for Route 53. Then you might wonder if one step goes wrong, will the whole setup fail?

Scenario: bucket name is different

  1. same name (Of course IT WORKS)

    subbbb.aws.domain.com
    # point to
    subbbb.aws.domain.com.s3-websit...
    
  2. Try using different name (FAILED)

    anothersub.aws.domain.com
    # point to
    subbbb.aws.domain.com.s3-websit...
    
    1. Route 53 blocks it first: when you create the A alias, the dropdown only lists S3 buckets with the same name as the record. With the record named anothersub, subbbb is not in the list.

    2. HACK: name the record subbbb first, and the subbbb bucket shows up in the dropdown. Pick it, then rename the record back to anothersub and save. The console does not check again, so the alias is saved.

    3. Opening anothersub.aws.domain.com still fails:

      # 404 Not Found
      - Code: NoSuchBucket
      - Message: The specified bucket does not exist
      - BucketName: **anothersub**.domain.com
      - RequestId: 6MTX7N8Z7KNGPBNP
      - HostId: JPiP....mofF7c=
      

DNS does resolve anothersub.aws.domain.com to subbbb's S3 website endpoint, but when S3 gets the request, it ignores which name DNS came from and reads the request's Host header. Here the Host is anothersub.aws.domain.com, so S3 looks for a bucket with that name, finds none, and answers NoSuchBucket. DNS and S3 are separate systems, and the name is the only thing that ties them together, which is why the bucket name has to match the domain.

Thought 2

What If: Route 53 Hosted Zone is set as domain.com, and inside it has aws.domain.com A record Alias to CloudFront or S3 Resource endpoint. If domain.com is currently hosted elsewhere like Github, will it affect the entire configuration?

Truth is: A hosted zone answers only if the level above delegates to it with NS records. The registrar's name servers for domain.com still answer domain.com (here with an A record pointing at GitHub's servers), and nothing sends queries to the Route 53 zone named domain.com. So the GitHub site is not taken over, but the aws.domain.com alias inside that zone is never looked up either: the configuration does not work.

So create the hosted zone as aws.domain.com instead, and add four NS records named aws, pointing at that zone's name servers, wherever domain.com's DNS is hosted. Then Route 53 answers aws.domain.com and nothing else; notaws.domain.com and the rest of domain.com stay where they are. Route 53 answers only what is delegated to it.

Footnotes

  1. The TXT record in Step 2 should be set in Route53, not your domain provider's. Because aws.domain.com is delegated to AWS name servers (step 3 of "Using Route 53"), names under aws.domain.com are answered by Route53. ↩

  2. Although the domain is specified when adding an SSL certificate, in CloudFront Distribution you still need to explicitly state which domain needs HTTPS protection in Alternate domain name. If not specified in CloudFront Distribution, even with a complete SSL certificate, it won't protect you. ↩