The setup, and the hole in it
stingrayio.com is files in an S3 bucket. The bucket is not public. CloudFront reads from it through origin access control, which means the distribution signs its requests and a bucket policy admits that one distribution and nobody else. There is no "static website hosting" switch turned on in S3; CloudFront talks to the plain REST endpoint of the bucket. This is the shape AWS recommends and the one I build by default: no anonymous access to the bucket, TLS between CloudFront and the origin, and the usual CloudFront tools, certificates, headers, logging, in front.
The REST endpoint serves objects by key. It does not know that
local/index.html has anything to do with a request for
local/. The one concession CloudFront makes is the
default root object, which maps a request for / to
index.html, and only for /. So the home
page worked from the day the distribution went up, and on October
26 I uploaded a second page at local/index.html,
opened https://stingrayio.com/local/, and got a 404.
The website endpoint of S3 would have handled it, because that
endpoint has an index-document setting that applies at every
level. The REST endpoint has nothing of the kind.
The function
CloudFront Functions run at the edge on every request, before the
cache is consulted, in a stripped-down JavaScript with a compute
budget of about a millisecond. That is exactly enough for this
job: look at the path, and either append index.html
or send the visitor to the path with the slash. This is the
function as it runs on this site, under a generic name of my own:
function handler(event) {
var request = event.request;
var uri = request.uri;
if (uri.endsWith('/')) {
request.uri = uri + 'index.html';
return request;
}
var last = uri.substring(uri.lastIndexOf('/') + 1);
if (last !== '' && last.indexOf('.') === -1) {
var qs = Object.keys(request.querystring).length
? '?' + Object.keys(request.querystring).map(function (k) {
return k + '=' + request.querystring[k].value;
}).join('&')
: '';
return {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: { location: { value: uri + '/' + qs } }
};
}
return request;
}
Two branches. A path ending in a slash gets index.html
appended and goes on to the origin as a rewritten request; the
visitor's address bar does not change. A path whose last segment
has no dot, like /local, is treated as a directory
typed without its slash and answered with a permanent redirect to
/local/, carrying the query string along. Anything
with an extension, /style.css or
/assets/mark.png, passes through untouched. The
redirect matters for more than tidiness: without it a page at
/local would load with relative links resolving
against the site root, and a search engine would see two addresses
for one page.
An earlier version of this function on a client's site did two
more things, because that site is laid out differently. It mapped
an extensionless path to a flat file, /about to
/about.html, and it redirected the www
host to the bare domain. Same mechanism, different convention.
Decide whether your site is directories or flat files before you
write the function, and write only the branches you need.
Where it attaches
A handful of API calls. Create the function with the code above and the
cloudfront-js-2.0 runtime, publish it from the
development stage to live, then read the distribution's
configuration, add the function's ARN to the
FunctionAssociations of the default cache behaviour
with event type viewer-request, and write the
configuration back with the ETag you read. Viewer-request is the
right hook because the rewrite has to happen before CloudFront
looks in its cache; otherwise /local/ and
/local/index.html would be cached as two different
objects, and one of them would be the 404.
I made this a repeatable target in my infrastructure tool rather than a console afternoon, with two properties worth copying. It is idempotent: it reads the function's current code from the development stage and compares it byte for byte with the source, so a second run writes nothing. And it refuses to proceed if the behaviour already has a different viewer-request function attached, because CloudFront allows exactly one per event type and silently replacing someone else's redirect logic is how outages start. The distribution update took about three minutes to deploy.
The two checks
Both from the command line, both against the live site, both still true today:
$ curl -sI https://stingrayio.com/local/ | head -1
HTTP/2 200
$ curl -sI https://stingrayio.com/local | grep -i "^HTTP\|^location\|^x-cache"
HTTP/2 301
location: /local/
x-cache: FunctionGeneratedResponse from cloudfront
The x-cache line on the redirect is the useful tell.
It says the response came from the function itself, never reached
the origin, and was not served from cache. If you see a 301 with
any other x-cache value, something else is issuing it.
A third check, that a path which really does not exist still
returns 404, confirms the function is not papering over missing
pages. It is not: the rewrite only adds index.html,
and if that object is not in the bucket the origin says so.
Why not the website endpoint
S3 has a second way to serve a bucket, the static website endpoint, and it understands index documents at every level. I did not switch to it, for two reasons that both come from how it is built. First, the website endpoint serves anonymous requests, so the bucket has to allow public reads, and origin access control does not apply; the bucket is reachable by anyone who learns its name, not only through the distribution. Second, the website endpoint speaks only HTTP, so CloudFront has to be configured to reach the origin without TLS. Neither is a disaster for a public marketing site. Both are the opposite of the posture I describe to clients, and I was not going to give up a private bucket and an encrypted origin connection to avoid twenty lines of JavaScript.
The other alternative, Lambda@Edge, does the same rewrite with a full Node runtime, cold starts and a regional deployment. For a path rewrite that is a much larger tool than the job needs. CloudFront Functions exist for exactly this class of problem, and the millisecond budget is a feature: it keeps you from putting anything in the request path that should not be there.
If your second page just returned 404
- Confirm the shape: a REST origin with origin access control and a default root object. If so, this is the cause, not a permissions problem.
- Write the function with only the branches your layout needs: directories, flat files, or both, plus a host redirect if you want one.
- Attach it on viewer-request of the default behaviour, not origin-request, so the cache sees the rewritten path.
- Check that nothing else is already attached on viewer-request before you write. There is room for one.
- Prove it with three requests: the directory with its slash, the directory without, and a path that does not exist. Expect 200, 301 to the slash, and 404.