Search Icon, Magnifying Glass

Graduation Cap Heart Question Mark Magnifying Glass

Hugo Site on S3 and CloudFront

For a very long time I’ve hosted this site at Nearly Free Speech. I’ve been happy at Nearly Free Speech, but with the launch of LectServe and other IoT and Serverless projects of mine on the AWS stack, it made logistical and financial sense to consolidate on Amazon.

Moving my Hugo site to Amazon was a fairly simple affair. First I setup a simple S3 bucket to drop my Hugo generated files to. Nothing special there at all. Next, I setup a CloudFront distribution to handle TLS and serve the files on S3. With a simple change in my domain’s DNS record everything worked perfectly. Perfectly except that all my URLs had to end in index.html to work…

Thankfully, Amazon recently pushed Lambda@Edge to be publically available. With a simple Node.js 6.10 Lambda triggered by a CloudFront origin-request event I can rewrite all requests so my pretty URLs continue to work.

'use strict';

exports.handler = (event, context, callback) => {
    let request = event.Records[0].cf.request;
    console.log(`Request uri originally set to "${request.uri}"`);
    const indexPath = new RegExp('/$');
    let match = indexPath.exec(request.uri);
    let newURL = request.uri;
    if(match) {
        newURL = `${request.uri}index.html`;

    console.log(`Request uri set to "${request.uri}"`);
    request.uri = newURL;
    callback(null, request);

So, that’s what you’re seeing now. With Lambda@Edge, S3, and a simple CloudFront distribution, it’s pretty easy to host your Hugo site on the AWS cloud.