Skip to main content
  1. blog/

🧽 Clean Static Site URLs with CloudFront and S3

·1 min

This site runs on Hugo which is a static site generator. Hugo automatically generates an index.html for each directory like /index.html, /blog/index.html, and so on.

The files live on an S3 bucket with CloudFront as the CDN. The S3 bucket is private with the static website hosting feature disabled so it is only accessible through CloudFront.

A common problem with this setup is that going to the clean URL like /blog results in a 403 Forbidden page.

CloudFront 403 Forbidden page

This is because S3 won’t return the index.html for subfolders when static website hosting is disabled. The request from CloudFront must contain index.html.

The solution for this is to create a function in CloudFront that will append index.html to any URLs ending in /.

async function handler(event) {
  const request = event.request;
  const 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;
}
From docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/example-function-add-index.html

Once the function has been created, you can update your CloudFront distribution under Behaviors > Function associations

CloudFront functions configuration