The tutorial version of "static site on S3 behind CloudFront" is about six
clicks. The version that survives a real domain, a real SPA router, and a real
deploy pipeline is not. Here are five places I lost time, and what actually
fixed each one.
1. Use the REST origin with OAC, not the website endpoint
A bucket gives you two different hostnames, and they behave differently:
-
bucket.s3-website-<region>.amazonaws.com - the website endpoint. Requires
the bucket to be publicly readable.
-
bucket.s3.<region>.amazonaws.com - the REST endpoint. Can stay completely
private and be reached only by CloudFront.
Pick the REST endpoint and put Origin Access Control (OAC) in front of it. OAC
is the current mechanism; Origin Access Identity (OAI) is the legacy one and you
shouldn't start new work on it. Leave S3 Block Public Access fully enabled and
let the bucket policy do the work:
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowCloudFrontServicePrincipalReadOnly",
"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/EDFDVBD6EXAMPLE"
}
}
}]
}
The AWS:SourceArn condition matters. Without it you've authorized the
CloudFront service principal broadly rather than your specific distribution.
2. The REST endpoint has never heard of an index document
This is the one that cost me the most time. CloudFront's "Default Root Object"
setting only applies to / . It does nothing for /blog/ or /docs/getting-started .
So the homepage works, you declare victory, and then every subdirectory returns
403 AccessDenied not even a 404, because listing isn't permitted and S3 won't
tell you whether the key exists.
The fix is a CloudFront Function on viewer request:
function 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;
}
CloudFront Functions run at the edge locations in sub-millisecond time and are
substantially cheaper than Lambda@Edge for something this small. Reach for
Lambda@Edge only when you need network calls or a real runtime.
3. Think twice before mapping every 404 to index.html
The standard SPA advice is a custom error response: 403 and 404 both return
/index.html with status 200 . It works, and for a pure client-rendered app it
may be what you want.
But be clear about the trade: after that change, every wrong URL on your domain
returns HTTP 200 with your app shell. Crawlers index nonexistent pages. Uptime
checks that look at status codes stop noticing broken links. A typo'd asset path
silently returns HTML where JavaScript was expected, which produces a
gloriously confusing parse error in the console.
If you can, keep genuine 404s as 404s either by rendering a real not-found page
from your router and returning the correct status where your framework allows,
or by pre-rendering known routes at build time so only truly missing paths fall
through.
4. The certificate must live in us-east-1
An ACM certificate used for a CloudFront alternate domain name has to be issued
in us-east-1, no matter where your bucket, your users, or the rest of your
stack are. Request it in ap-southeast-1 and it simply will not appear in the
distribution's certificate dropdown with no explanation as to why.
Second gotcha in the same area: a wildcard *.example.com certificate does not
cover the apex example.com . If you serve both, request the certificate with
both names on it.
5. Stop invalidating /* on every deploy
Invalidating the whole distribution on each release is slow and, past the free
1,000 paths per month, billed per path. It's also unnecessary if you set cache
headers correctly at upload time.
The pattern: build tools already emit content-hashed filenames like
app.4f2a9c.js . A hashed file's content can never change, so cache it forever.
Only the entry HTML needs to be fresh.
# Hashed assets: cache hard
aws s3 sync ./dist s3://YOUR-BUCKET --delete \
--cache-control "public,max-age=31536000,immutable" \
--exclude "index.html"
# Entry point: always revalidate
aws s3 cp ./dist/index.html s3://YOUR-BUCKET/index.html \
--cache-control "no-cache"
# Now the invalidation is two paths, not the whole distribution
aws cloudfront create-invalidation \
--distribution-id EDFDVBD6EXAMPLE --paths "/" "/index.html"
Note that no-cache is not no-store . no-cache still allows the object to be
stored it just requires revalidation before reuse, which is exactly what you
want for an entry document.
One caveat on --delete : it removes the previous build's hashed assets
immediately. A user who loaded the old index.html thirty seconds before your
deploy will request chunks that no longer exist. If that matters, keep old
assets around and expire them with an S3 lifecycle rule instead of deleting on
sync.
Wrapping up
None of these are exotic. They're just the gap between the happy path in the
console and a setup you'd be comfortable pointing a real domain at. If you're
building this out for the first time, the order I'd suggest is: get OAC and the
bucket policy right first, add the index-document function immediately after,
and leave the caching strategy until you have a deploy script worth optimizing.
What tripped you up on your first CloudFront distribution? I'd be curious
whether the index-document thing catches everyone or just me.
Loading article