// 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.
- Buildgenerate the static files (Gatsby or any bundler)
- Syncupload hashed assets with long cache headers
- Upload HTMLshort cache so content updates appear quickly
- Plan gate gateterraform plan reviewed before any infrastructure change
- ACMcertificate requested in us-east-1, validated through Route 53
- CloudFrontdistribution with OAC to the private bucket
- Route 53A and AAAA alias records for apex and www
- Invalidateinvalidate /index.html and other HTML paths after each deploy
// 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
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.
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.
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_optionsand write them to Route 53. Theaws_acm_certificate_validationresource is the important one: it blocks until ACM reports the certificate issued, which is what makes the dependency order correct.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.
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.
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.
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.comand confirm HTTP/2 200 with avia: ... cloudfrontheader. - Run
curl -sI https://<bucket>.s3.<region>.amazonaws.com/index.htmland 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 cloudfronton 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 = trueyou 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
- Add a response headers policy for HSTS, CSP and frame protections.
- Attach AWS WAF with a rate rule if the site takes form posts.
- Wrap the module for reuse, the same pattern as in One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling.
- Compare with the edge delivery in Serverless Video-on-Demand with MediaConvert, CloudFront and Cognito.