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
-
Navigate to
CloudFront
in your AWS Console -
Click on
Functions
in the left panel -
Click on
Create Function
on the top right of your page -
Name your function (I used
index_html
) >Create Function
-
Select your function (i.e.
index_html
)
- 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;
}
-
Click on
Save changes
-
Navigate to the
Publish
tab -
Click on
Publish Function
- 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!