Append index.html To Static Site Routing With AWS CloudFront

#aws #gatsby #cloudfront #jotthatdown

Profile picture

Age: 28

Profession: Engineer

Location: 🇺🇸

Introduction

Having trouble with AWS CloudFront and trailing forward slashes on your static sites? So was I.

With some experience in setting up static sites in AWS S3, I have had some troubles with migrating to Gatsby. This is due to some routing inconsistencies between Gatsby and CloudFront. I found that initially when deploying a Gatsby Starter Blog to S3 and CloudFront, you would receive and initial 404 before being redirected to the absolute path. This is due to CloudFront expecting */index.html, but Gatsby only providing a absolute path of /.

In this document we will walk through how to route every call to your static site to */index.html.

How To

  1. Navigate to CloudFront in your AWS Console

  2. Click on Functions in the left panel

  3. Click on Create Function on the top right of your page

  4. Name your function (I used index_html) > Create Function

  5. Select your function (i.e. index_html)

index_html

  1. Add the following block of code to to the Function code section
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;
}

index_html_code

  1. Click on Save changes

  2. Navigate to the Publish tab

  3. Click on Publish Function

index_html_code

  1. The last step is to associate the function to your CloudFront distribution!

Result

At this point your navigation and routing woes with CloudFront and Gatsby or other static site generators should be solved!


Profile picture

Jotted down by JotThatDown