When I originally setup the infrastructure to serve my static site (for Evolving Architecture: Publishing a Jekyll site to AWS using GitHub Actions and AWS CDK) I manually set things up in the AWS console.

Sue me, I'm an idiot 😉

One thing I hadn’t realised in doing this was that I setup the bucket to return an index.html if a directory was requested, rather than a file. However I didn’t replicate that into my CDK stack.

And doing a bit of testing revealed this.

Doofus

Doing some quick reading I soon found Cloudfront Functions and the sample to add index.html to request URLs that don’t include a file name.

function handler(event) {
    var request = event.request;
    var uri = request.uri;

    // Check whether the URI is missing a file name.
    if (uri.endsWith('/')) {
        request.uri += 'index.html';
    }
    // Check whether the URI is missing a file extension.
    else if (!uri.includes('.')) {
        request.uri += '/index.html';
    }
    
    return request;
}

But how to deploy this via CDK? Idan Lupinsky’s: Static Site Deployment using AWS CloudFront, S3 and the CDK quickly provided the answer.

const rewriteFunction = new Function(this, 'codemunkies-urlrewrite-function', {
    code: FunctionCode.fromFile({ filePath: 'cfd-fn/url-rewrite.js' }),
});

const distribution = new Distribution(this, 'codemunkies-distribution', {
    certificate: certificate,
    defaultRootObject: 'index.html',
    defaultBehavior: {
        functionAssociations: [{
            function: rewriteFunction,
            eventType: FunctionEventType.VIEWER_REQUEST
        }],
        origin: new S3Origin(bucket, {originAccessIdentity}),
        viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    },
    domainNames: [ 'beta.codemunki.es' ],
});

While the function is undoutedly basic, and doesn’t cover every conceivable situation, it’s a starting point.

The full change is available in pull request #3.