Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 70 ยท Real-world projects

Project: Static Site on S3 and CloudFront

Build a fast, cheap static website step by step: private S3 bucket, CloudFront with OAC, ACM certificate, Route 53 alias and a CI deploy script with invalidation.

In this project you will host a static website, such as a documentation site, portfolio or marketing page, the way many production teams do: files in a private S3 bucket, CloudFront in front for speed and HTTPS, an ACM certificate for the domain, and Route 53 to point the domain at the distribution. A deploy script then uploads changes and tells the CDN what to refresh. The result costs very little, scales to a traffic spike without help and has no server to patch.

The real services need an AWS account, so the commands, JSON and workflow files below are read-only. They are accurate patterns you can adapt, with placeholder names such as example.com. Two Python stand-ins make the interesting logic visible on this page: a planner that works out which files a deploy must upload, and one that decides which cache paths to invalidate. These are teaching emulators, not the AWS tools. The background is in S3 Buckets and Objects, Static Websites and S3 Events and CloudFront CDN.

The design

flowchart LR
    DEV["Developer pushes<br/>to main"] --> CI["CI job<br/>(GitHub Actions)"]
    CI -- "sync files" --> S3["S3 bucket<br/>(private)"]
    CI -- "invalidate" --> CF
    R53["Route 53<br/>www.example.com (alias)"] --> CF["CloudFront distribution"]
    ACM["ACM certificate<br/>(us-east-1)"] -.-> CF
    CF -- "signed requests (OAC)" --> S3
    U["Readers"] --> R53

Readers only talk to CloudFront; CloudFront alone may read the bucket; CI is the only writer.

Notice what is missing: the bucket has no public access and no website hosting endpoint. CloudFront uses Origin Access Control (OAC) to sign its requests to the S3 REST endpoint, and the bucket policy trusts only that one distribution. This is the recommended modern setup and it keeps direct bucket URLs closed.

Step 1: a private bucket

Use a name you control, such as example-com-site-prod. New buckets have Block Public Access enabled by default, which is exactly what you want here.

Terminal
aws s3api create-bucket \
  --bucket example-com-site-prod \
  --region eu-west-1 \
  --create-bucket-configuration LocationConstraint=eu-west-1

aws s3api put-public-access-block \
  --bucket example-com-site-prod \
  --public-access-block-configuration \
  BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

Do not enable the S3 static website endpoint for this design. That endpoint only works with public buckets, which is the thing you are avoiding.

Step 2: the certificate

CloudFront reads certificates only from us-east-1, whatever Region your bucket uses. Request a public certificate with DNS validation, then create the CNAME record that ACM shows you in your Route 53 zone. Validation usually completes within minutes, and the certificate renews automatically as long as that record stays.

Terminal
aws acm request-certificate \
  --region us-east-1 \
  --domain-name www.example.com \
  --subject-alternative-names example.com \
  --validation-method DNS

Step 3: the Origin Access Control

JSON
{
  "Name": "example-com-site-oac",
  "Description": "CloudFront to the private site bucket",
  "SigningProtocol": "sigv4",
  "SigningBehavior": "always",
  "OriginAccessControlOriginType": "s3"
}
Terminal
aws cloudfront create-origin-access-control \
  --origin-access-control-config file://oac.json

Step 4: the distribution

The configuration below is abbreviated to the parts that matter. The managed cache policy CachingOptimized has the id shown and respects the Cache-Control headers you set on your objects within sensible limits.

JSON
{
  "CallerReference": "example-com-2026-01",
  "Comment": "example.com static site",
  "Enabled": true,
  "Aliases": { "Quantity": 2, "Items": ["www.example.com", "example.com"] },
  "DefaultRootObject": "index.html",
  "Origins": {
    "Quantity": 1,
    "Items": [{
      "Id": "site-bucket",
      "DomainName": "example-com-site-prod.s3.eu-west-1.amazonaws.com",
      "S3OriginConfig": { "OriginAccessIdentity": "" },
      "OriginAccessControlId": "E1EXAMPLEOAC"
    }]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "site-bucket",
    "ViewerProtocolPolicy": "redirect-to-https",
    "Compress": true,
    "AllowedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] },
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6"
  },
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      { "ErrorCode": 403, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 60 },
      { "ErrorCode": 404, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 60 }
    ]
  },
  "ViewerCertificate": {
    "ACMCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/EXAMPLE",
    "SslSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  },
  "PriceClass": "PriceClass_100"
}

Why the 403 mapping? When a bucket denies listing, S3 answers a request for a missing key with 403 Forbidden instead of 404, so CloudFront needs to turn both into your friendly 404 page. PriceClass_100 serves from the cheapest set of edge locations, which is fine for a mostly regional audience. Remember that DefaultRootObject only covers the site root: a request for /docs/ does not automatically become /docs/index.html. Either link to full file names, generate files as docs.html, or add a small CloudFront Function that rewrites directory paths.

Step 5: let only this distribution read the bucket

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowCloudFrontRead",
    "Effect": "Allow",
    "Principal": { "Service": "cloudfront.amazonaws.com" },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::example-com-site-prod/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/E1EXAMPLEDIST"
      }
    }
  }]
}

The condition on AWS:SourceArn matters: without it, any CloudFront distribution in any account could read your bucket. See S3 Security for how bucket policies are evaluated.

Step 6: point the domain at it

In Route 53, create an alias A record (and an AAAA record for IPv6) for www.example.com that targets the distribution's dxxxxxxxx.cloudfront.net name. The hosted zone id used for any CloudFront alias is the fixed value Z2FDTNDATAQYW2. Alias records are free for queries and work at the zone apex, unlike CNAME (Route 53 and DNS).

Terminal
aws route53 change-resource-record-sets --hosted-zone-id Z0EXAMPLEZONE --change-batch '{
  "Changes": [{
    "Action": "UPSERT",
    "ResourceRecordSet": {
      "Name": "www.example.com",
      "Type": "A",
      "AliasTarget": {
        "HostedZoneId": "Z2FDTNDATAQYW2",
        "DNSName": "d111111abcdef8.cloudfront.net",
        "EvaluateTargetHealth": false
      }
    }
  }]
}'

Step 7: the deploy script

A good deploy has two kinds of files and treats them differently. Build tools add a content hash to asset names (app.3f9a1c.js), so a file name never changes meaning, and those files can be cached for a year. HTML files keep stable names and must be revalidated, so give them a short cache time.

Terminal
#!/usr/bin/env bash
set -euo pipefail
BUCKET=example-com-site-prod
DIST=E1EXAMPLEDIST

# 1. hashed assets: cache for a year, never revalidate
aws s3 sync ./dist "s3://$BUCKET" --exclude "*.html" --delete \
  --cache-control "public,max-age=31536000,immutable"

# 2. HTML: short cache so changes appear quickly
aws s3 sync ./dist "s3://$BUCKET" --exclude "*" --include "*.html" --delete \
  --cache-control "public,max-age=60,must-revalidate"

# 3. refresh the pages that changed
aws cloudfront create-invalidation --distribution-id "$DIST" --paths "/" "/index.html"

In CI, do not store long-lived access keys. With GitHub Actions you can use OpenID Connect so the job assumes an IAM role for a few minutes (IAM Users, Groups and Roles explains why):

YAML
name: deploy
on:
  push:
    branches: [main]
permissions:
  id-token: write
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm run build
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111122223333:role/site-deployer
          aws-region: eu-west-1
      - run: ./deploy.sh

The role needs only s3:PutObject, s3:DeleteObject and s3:ListBucket on this bucket plus cloudfront:CreateInvalidation on this distribution, and its trust policy should name your repository.

Stand-in 1: what does a sync upload?

aws s3 sync compares local files with the bucket and copies what differs. The emulator below does the same using a hash per file, sets the cache header by file type and shows what --delete would remove.

Python Plan a sync: uploads, deletes and cache headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the old app.11aa22.js is deleted and app.99ee88.js is new. Because the new HTML points at the new name, no cache anywhere can serve a mismatched pair for long. That property is what makes fingerprinted assets safe to cache for a year.

Stand-in 2: which paths to invalidate

An invalidation removes objects from the edge caches before their TTL ends. It is fast to request but not free in the long run: the first 1,000 paths per month are free and further paths are charged, so check current pricing. A wildcard such as /blog/* counts as one path. The planner below decides what to send. Two rules are worth noticing: hashed assets never need invalidation, and / and /index.html are different cache entries, so both must be listed.

Python Plan a CloudFront invalidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real deployments often invalidate /* and accept the single path, which is simple and cheap in cost. The trade-off is that every object returns to a cold cache, so the next requests all go to S3. Targeted invalidation keeps the hit ratio high on large sites.

Checks before you call it done

  • Request the site over HTTP and confirm it redirects to HTTPS.
  • Open a bucket URL directly (https://example-com-site-prod.s3.eu-west-1.amazonaws.com/index.html) and confirm you get AccessDenied.
  • Look at the response headers: x-cache: Hit from cloudfront on a second request shows the cache works.
  • Set a budget alert so a traffic surge never surprises you.
  • Keep Terraform or CloudFormation templates for all of this, so the site can be recreated (CloudFormation).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the bucket kept private and read through Origin Access Control?

    OAC lets CloudFront sign requests to S3, and the bucket policy trusts only that distribution, so nobody can bypass the CDN.
  2. 2. In which Region must the ACM certificate for a CloudFront distribution be requested?

    CloudFront reads viewer certificates from us-east-1, whichever Region your origin is in.
  3. 3. Why can hashed asset files such as app.99ee88.js be cached for a year?

    Content hashing means a name always maps to the same bytes; updates arrive under new names, referenced by fresh HTML.
  4. 4. After changing index.html, which paths should you invalidate?

    The cache key is the requested path, so the root URL and the explicit file name are cached separately.

Summary

  • Keep the bucket private, read it through CloudFront with OAC, and restrict the bucket policy to one distribution with AWS:SourceArn.
  • Request the ACM certificate in us-east-1 and validate it with DNS; point the domain at CloudFront with an alias record.
  • Give hashed assets a one-year immutable cache and HTML a short revalidated cache.
  • Deploy with s3 sync and a targeted invalidation, and authenticate CI with OIDC and a narrow role instead of stored keys.
  • Verify that HTTP redirects, direct bucket access is denied and cache hits appear.

Next: Project: Serverless REST API.