Configuring AWS CloudFront With S3 for Static Website Delivery
Keep the bucket private, serve through CloudFront, add HTTPS and a custom domain, and invalidate cleanly.
- aws
- cloudfront
- s3
- https
- cdn
On this page ยท 14 sections
Serving a website straight from an S3 website endpoint works, but it has limits: no HTTPS, no custom domain with TLS, a public bucket and no edge caching. Amazon CloudFront fixes all four. This guide puts CloudFront in front of a private S3 bucket using Origin Access Control, adds HTTPS on your own domain, handles single-page-app routing and sets up a clean deployment and invalidation workflow.
It assumes you already have a static site in an S3 bucket. If not, start with the guide on hosting a static website on AWS S3.
The target architecture
- 1Browser
HTTPS request
- 2CloudFront
edge cache, TLS, custom domain
- 3S3 bucket (private)
read through a signed OAC request
The bucket stays private. Only the CloudFront distribution is allowed to read it, which removes a whole category of mistakes caused by public buckets.
Why use CloudFront here
- HTTPS everywhere with a free certificate from AWS Certificate Manager.
- Lower latency because content is cached at edge locations near users.
- A private bucket, so objects cannot be fetched directly from S3.
- Compression (gzip and Brotli) handled for you.
- Control over caching and headers per path.
Step 1: Request a certificate (us-east-1)
CloudFront reads TLS certificates from US East (N. Virginia), regardless of where your bucket lives. Switch the console region to us-east-1, open AWS Certificate Manager, and request a public certificate for your domain (and www if you use it):
aws acm request-certificate \ --region us-east-1 \ --domain-name example.com \ --subject-alternative-names www.example.com \ --validation-method DNSAdd the CNAME records ACM shows you to your DNS zone. With Route 53 the console can create them in one click. Wait until the status is Issued before creating the distribution.
Step 2: Create the distribution
In the CloudFront console choose Create distribution and set:
- Origin domain: pick the bucket's S3 REST endpoint (
my-bucket.s3.us-east-1.amazonaws.com), not the website endpoint. - Origin access: Origin access control settings (recommended) โ create a new OAC (signing behavior: Sign requests).
- Viewer protocol policy: Redirect HTTP to HTTPS.
- Default root object:
index.html. - Compress objects automatically: on.
- Alternate domain names (CNAMEs):
example.com,www.example.com. - Custom SSL certificate: choose the ACM certificate from Step 1.
For the cache policy, the managed CachingOptimized policy is a good default for static assets.
When you create the distribution, the console shows a ready-made bucket policy for the OAC. Copy it.
Step 3: Allow only CloudFront to read the bucket
Replace any public-read policy with one that trusts CloudFront and is scoped to your distribution:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipalReadOnly", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1ABCDEXAMPLE" } } } ]}The AWS:SourceArn condition is what ties access to this one distribution. Without it, any CloudFront distribution in any account could request your objects through the service principal.
Now turn Block Public Access back on for the bucket. The site keeps working because CloudFront reads it through the policy above, while direct S3 URLs return an access error.
Step 4: Fix single-page-app routing
If your site is a single-page app, a request for /dashboard looks for an object that does not exist. With a private bucket and OAC, S3 answers 403 Forbidden (CloudFront has no ListBucket permission, so S3 hides whether the object exists). Map the errors to your app shell under Error pages โ Create custom error response:
| HTTP error code | Response page path | HTTP response code |
|---|---|---|
| 403 | /index.html | 200 |
| 404 | /index.html | 200 |
Set an error caching minimum TTL of around 10 seconds so a bad deploy does not stay cached for long.
If your site is a static export where every route has its own HTML file (about/index.html), CloudFront's default root object only applies to the site root, not to subfolders. A small CloudFront Function can rewrite /about/ to /about/index.html:
// CloudFront Function: viewer requestfunction handler(event) { var request = event.request; var uri = request.uri; if (uri.endsWith("/")) { request.uri += "index.html"; } else if (!uri.includes(".")) { request.uri += "/index.html"; } return request;}Step 5: Point your domain at CloudFront
In Route 53, create alias records (type A, and AAAA if IPv6 is enabled) for example.com and www.example.com targeting the distribution. Alias records work at the zone apex, which a normal CNAME cannot. If your DNS is elsewhere, create a CNAME for www to the dxxxxxxxx.cloudfront.net domain and use your provider's ALIAS/ANAME feature for the apex.
dig +short example.comcurl -I https://example.comLook for HTTP/2 200, a via: ... (CloudFront) header and x-cache: Hit from cloudfront on repeat requests.
Step 6: Deploy and invalidate
A good deploy has two parts: upload with the right cache headers, then invalidate only what could be stale.
#!/usr/bin/env bashset -euo pipefailBUCKET=my-bucketDISTRIBUTION_ID=E1ABCDEXAMPLEnpm run build# Fingerprinted files: cache for a yearaws s3 sync dist "s3://$BUCKET" --delete \ --exclude "index.html" \ --cache-control "public,max-age=31536000,immutable"# Entry point: always revalidateaws s3 cp dist/index.html "s3://$BUCKET/index.html" \ --cache-control "no-cache" --content-type "text/html"# Only the files that keep the same name need invalidatingaws cloudfront create-invalidation \ --distribution-id "$DISTRIBUTION_ID" \ --paths "/index.html"Because bundlers produce new filenames for changed assets, you do not need /* on every deploy. Invalidate /index.html (and any other unhashed files, like a sitemap or robots.txt). AWS includes a number of free invalidation paths each month, but wildcard invalidations still add up and are slower than they need to be.
Security considerations
- Keep the bucket private and the OAC policy scoped with
AWS:SourceArn. - Use a security headers policy (managed or custom response headers policy) to add
Strict-Transport-Security,X-Content-Type-Optionsand a Content Security Policy. - Keep the TLS security policy current (the default
TLSv1.2_2021or newer). - Deploy from CI using a role with only the S3 and invalidation permissions it needs.
- Consider AWS WAF if the site accepts any user input or you need rate limiting.
Performance considerations
- Enable HTTP/2 and HTTP/3 on the distribution.
- Leave automatic compression on, and make sure files are cacheable so compression is applied once at the edge.
- Use long TTLs for hashed assets and short or
no-cachefor HTML. - Pick the price class that matches your audience instead of all edge locations if cost matters.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
AccessDenied XML from CloudFront | Bucket policy missing or wrong distribution ARN | Re-check the OAC bucket policy |
| 403 on page refresh | SPA routes with no custom error response | Add the 403/404 โ /index.html mapping |
| Old site after deploy | Cached index.html | Invalidate /index.html, check Cache-Control |
| Certificate not in dropdown | ACM certificate not in us-east-1 | Request it again in us-east-1 |
ERR_SSL_VERSION_OR_CIPHER_MISMATCH | Domain not listed in the distribution's alternate names | Add the CNAME and certificate |
| Domain does not resolve | DNS record missing or still propagating | Check the alias record with dig |
/about/ returns the homepage | Subfolder index not resolved | Use the CloudFront Function above |
Testing and validation
# Is the response served over HTTPS and from CloudFront?curl -sI https://example.com | grep -iE "HTTP/|x-cache|via|cache-control"# Is the bucket really private? (expect 403)curl -sI https://my-bucket.s3.us-east-1.amazonaws.com/index.html# A deep link should return your app, not an errorcurl -sI https://example.com/dashboardBest practices
- Prefer OAC over the legacy OAI and over public buckets.
- Describe the whole setup in infrastructure as code (CDK or Terraform) so it is reproducible.
- Keep separate distributions for staging and production.
- Version your bucket if you want one-step rollbacks.
- Track CloudFront metrics (error rate, cache hit ratio) in CloudWatch.
Conclusion
CloudFront turns an S3 bucket into a production static site: private storage, HTTPS on your domain, edge caching and clean deploys. The key details are easy to miss, a certificate in us-east-1, the S3 REST endpoint as the origin, a bucket policy scoped to your distribution, and error mappings for single-page-app routes. Get those right and the rest is a repeatable deploy script.
Frequently asked questions
+Why use CloudFront instead of the S3 website endpoint?
The S3 website endpoint is HTTP only and serves from one region. CloudFront adds HTTPS, a custom domain, edge caching, compression and security headers, and lets the bucket stay completely private.
+What is Origin Access Control (OAC)?
OAC lets CloudFront sign its requests to S3 so only your distribution can read the bucket. It replaces the older Origin Access Identity (OAI) and supports newer S3 features such as SSE-KMS encryption.
+Why must my ACM certificate be in us-east-1?
CloudFront is a global service that reads certificates from the US East (N. Virginia) region. A certificate created in any other region will not appear in the CloudFront certificate list.
+Why does my single-page app return 403 on refresh?
With a private bucket and OAC, a missing object returns 403 (not 404) because CloudFront has no ListBucket permission. Add custom error responses that map 403 and 404 to /index.html with a 200 status.
+Do I have to invalidate the cache on every deploy?
Not for fingerprinted assets, because new builds produce new filenames. You only need to invalidate files that keep the same name, mainly index.html. Invalidating /index.html is cheaper and faster than invalidating everything.
+Should I use the S3 REST endpoint or the website endpoint as the origin?
Use the S3 REST endpoint (bucket.s3.region.amazonaws.com) with OAC for a private bucket. The website endpoint requires a public bucket and cannot use OAC, so only choose it if you need S3 redirect rules or automatic index documents in subfolders.
+How long does a new distribution take to deploy?
Typically a few minutes, but changes propagate to all edge locations asynchronously. Check the distribution status in the console and wait for Deployed before testing.