Cloud / IaC · Freelance

Host a Global Static Website on S3 and CloudFront with ACM SSL and a Custom Domain

Terraform for a private S3 bucket behind CloudFront with an ACM certificate, Route 53 aliases, SPA routing and a cache-invalidating deploy script.

  • S3
  • CloudFront
  • ACM
  • Route 53
  • Terraform
  • Origin Access Control
  • Gatsby
  • GitHub Actions

// Why this matters

To host a static website on S3 and CloudFront the right way you need more than a public bucket: you need HTTPS on your own domain, the site served from the edge, and a deploy process that does not leave visitors looking at yesterday's page. Done well it costs cents per month and never needs patching, which is why it is the default choice for brochure sites, documentation and single page applications.

Clients asked for this repeatedly, usually after discovering that the S3 website endpoint cannot do HTTPS at all. The build was always the easy part. Certificates, DNS and cache behaviour were where the hours went, so a reusable module paid for itself quickly.

// The problem

The S3 website endpoint serves HTTP only and requires the bucket to be public. That fails any modern security review and breaks the moment a browser enforces HTTPS. Putting CloudFront in front fixes TLS, but introduces new moving parts: the certificate must live in us-east-1 regardless of where everything else is, DNS validation must complete before the distribution can be created, and the old Origin Access Identity approach is being replaced.

Caching causes the other class of bugs. Without an invalidation or sensible headers, a deploy appears to work and then half the users see the old HTML for a day. With an invalidation of everything on every deploy you pay for it and still get race conditions between HTML and assets.

Single page applications add a final wrinkle: a deep link like /account/settings has no object in S3, so the origin returns 403 or 404 and the app never gets a chance to route.

// The solution

The module has five parts: a private bucket, an OAC and bucket policy, an ACM certificate with DNS validation, a distribution and the Route 53 records. The bucket blocks all public access and the policy allows only the specific distribution ARN, so even a leaked bucket name exposes nothing.

I use Origin Access Control rather than the legacy Origin Access Identity. OAC supports SSE-KMS buckets, signs with SigV4 and is the documented path forward. The bucket policy references the distribution by ARN, which creates a dependency cycle if done carelessly, so the policy is a separate resource that depends on the distribution.

Cache strategy is split by file type. Build tools such as Gatsby emit hashed filenames for JS, CSS and images, so those are uploaded with a one-year immutable header and never invalidated. HTML and the sitemap get a short max-age and are invalidated on deploy. That keeps invalidations to a handful of paths, well inside the free monthly allowance.

For SPA routing I map 403 and 404 responses to /index.html with status 200. A CloudFront Function handles the www redirect at the viewer-request stage so one distribution serves both names. The alternative of two distributions doubles the certificates and the invalidation logic for no benefit.

How it flows flow1. Build → 2. Sync → 3. Upload HTML → 4. Plan gate → 5. ACM → 6. CloudFront → 7. Route 53 → 8. Invalidate01Build02Sync03Upload HTML04 · GATEPlan gate05ACM06CloudFront07Route 5308Invalidate
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Buildgenerate the static files (Gatsby or any bundler)
  2. Syncupload hashed assets with long cache headers
  3. Upload HTMLshort cache so content updates appear quickly
  4. Plan gate gateterraform plan reviewed before any infrastructure change
  5. ACMcertificate requested in us-east-1, validated through Route 53
  6. CloudFrontdistribution with OAC to the private bucket
  7. Route 53A and AAAA alias records for apex and www
  8. Invalidateinvalidate /index.html and other HTML paths after each deploy
DNSRoute 53 alias ARoute 53 alias AAAAEdgeCloudFrontACM certificateViewer request functionOrigin accessOAC SigV4Bucket policyOriginPrivate S3 bucketVersioning
Request path. Nothing about the bucket is public.
TerraformACMRoute 53CloudFrontrequest certificate (DNS validation)return validation CNAMEcreate validation recordcheck record, issue certificatecreate distribution with certificatecreate alias records
Certificate issuance. Terraform waits for validation before building the distribution.

// Before you start

  • Terraform 1.5 or newer and AWS provider 5.x
  • A Route 53 hosted zone for the domain, or the ability to create DNS records at your registrar
  • AWS CLI v2 configured with permission for S3, CloudFront, ACM and Route 53
  • A static build directory, for example public/ from Gatsby or dist/ from Vite
  • Basic understanding of DNS records and HTTP caching headers

// Step-by-step implementation

  1. 01 Providers and the us-east-1 alias

    CloudFront only accepts certificates from us-east-1. If your main provider points elsewhere you need a second aliased provider just for ACM. Declaring it up front avoids the classic error where the certificate exists but cannot be attached.

  2. 02 Create the private bucket

    Block every form of public access and turn on versioning so a bad deploy can be rolled back by restoring object versions. Server-side encryption is on by default now, but declaring it makes the intent explicit.

  3. 03 Request and validate the ACM certificate

    Request the apex and the wildcard or www name on one certificate. The validation records are derived from the certificate, so we loop over domain_validation_options and write them to Route 53. The aws_acm_certificate_validation resource is the important one: it blocks until ACM reports the certificate issued, which is what makes the dependency order correct.

  4. 04 Origin Access Control and the distribution

    The distribution uses the bucket regional domain name as its origin and OAC to sign requests. Default root object is index.html. The managed CachingOptimized policy is a sensible default; HTML freshness is controlled by headers set at upload and by invalidation.

    Custom error responses turn missing objects into the SPA shell. If your site is multi-page static HTML, point the 404 mapping at a real 404.html instead.

  5. 05 Bucket policy that trusts only this distribution

    The policy allows the CloudFront service principal to read objects, conditioned on the distribution ARN. Because it references the distribution, it must be its own resource; embedding it in the bucket resource creates a cycle.

  6. 06 Route 53 alias records for apex and www

    Alias records point at the distribution without a CNAME, which is the only way to serve the zone apex. Create both A and AAAA so IPv6 clients are served from the edge too. CloudFront always uses the same hosted zone id for aliases, exposed by the resource.

  7. 07 Deploy script with correct cache headers and invalidation

    Upload in two passes. First sync everything except HTML with a one-year immutable header, deleting removed files. Then upload HTML with a short max-age. Only then invalidate the HTML paths. The order matters: if HTML references new hashed assets, those assets must already exist when the new HTML goes live.

    The script reads the bucket and distribution id from Terraform outputs, so the same script works for every site built from the module.

// How to verify it works

  • Run curl -sI https://example.com and confirm HTTP/2 200 with a via: ... cloudfront header.
  • Run curl -sI https://<bucket>.s3.<region>.amazonaws.com/index.html and confirm 403, proving the bucket is private.
  • Open the site, view the certificate and confirm it is issued by Amazon for both the apex and www names.
  • Request a hashed asset twice and confirm x-cache: Hit from cloudfront on the second response.
  • Deploy a content change and confirm the new HTML appears within a minute after the invalidation completes.
  • Visit a deep link such as /account/settings and confirm the SPA loads rather than an XML error.

// Design decisions and trade-offs

  • Keep the bucket fully private and let CloudFront read it through Origin Access Control
  • Issue the certificate in us-east-1 with DNS validation so renewal is hands-off
  • Version asset filenames and invalidate only HTML so deploys are cheap
  • Rewrite 403 and 404 to index.html for single page apps, but not for real asset paths
  • Redirect www to the apex in the distribution instead of running a second site

// Pitfalls and lessons learned

  • Creating the certificate in the wrong region is the single most common failure; CloudFront will not list it.
  • Deleting ACM validation records breaks renewal months later, when nobody remembers why they exist.
  • Mapping 404 to index.html with status 200 makes missing images return HTML; scope it to routes, or use a function that checks for a file extension.
  • Invalidating /* on every deploy works but wastes the free allowance and still races with asset uploads.
  • The bucket policy referencing the distribution inside the bucket resource creates a Terraform cycle; keep it separate.
  • Without compress = true you ship uncompressed JS even though the origin has gzip candidates.
  • Changing aliases without the new names on the certificate gives a confusing 403 from CloudFront rather than a TLS error.

// Frequently asked questions

How do I host a static website on S3 and CloudFront with a custom domain?

Create a private bucket, an ACM certificate in us-east-1 validated by DNS, a CloudFront distribution with Origin Access Control, then alias records in Route 53. The Terraform in this post does all of it.

Why does CloudFront need the certificate in us-east-1?

CloudFront is a global service that reads certificates from a single control-plane region, which is us-east-1. The rest of your stack can be anywhere.

Should I use the S3 website endpoint instead?

Only for plain HTTP prototypes. It requires a public bucket and cannot terminate TLS with your certificate. OAC to a private bucket is safer and supports HTTPS.

How do I clear the CloudFront cache after deploying?

Create an invalidation for HTML and data paths only, and give hashed assets immutable cache headers so they never need invalidating.

Can I use this for a Gatsby site that reads from WordPress?

Yes. Gatsby builds static files at deploy time; host them as above and rebuild on content change. The WordPress back office can run elsewhere, see Per-Client WordPress Hosting with Packer, Terraform and Ansible.

// The outcome

Static front ends, including Gatsby builds with a WordPress back office, are served from the edge over HTTPS with certificates that renew themselves. The same module has been reused for several sites, so a new domain is a variable file and a plan.

// Where to take it next

// Keep reading