TOC
The problem
One of the problems with hosting a simple static site using a creator/framework tool like Jekyll or Hugo, and publishing it via Cloudfront is that links within the site can often be missing the index.html
suffix, which is vital for when cloudfront is trying to reach the origin object in S3.
For example, the “About” page on this site is contained within /about/index.html
, however all links to the “About” page are simply /about/
. The problem is that cloudfront will simply try to find a key in the origin S3 bucket named /about/
, however this doesn’t technically exist (it’s a prefix, not an object). So therefore, we need a way for cloudfront to redirect these types of links to go to the index.html
document contained in S3.
Previously, in order to do this you’d need to create a Lambda@Edge function, of which there’s a great guide here on the AWS site. This was (and still is) a great option for manipulating data in your Cloudfront distrubutions at the Edge. Now however, AWS have introduced Cloudfront Functions, which is essentially a much more basic service for running functions at the Edge, and is perfect what what we need to achieve here.
The Fix - Setting up a Cloudfront Function
So just to recap - we need to create a function that will run at the Edge to add index.html
to our links that previously missed them off (e.g. /about/
).
- So let’s head over to the Cloudfront console, and click the new Functions option on the left, then Create Function
- Give it a suitable name and description, then click Create Function
- Inside the function, head down to Function Code and paste in the below Javascript code, then click Save Changes
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; }
- Head to the Test tab, and in the URL Path, enter a suitable path to test with
- Click Test Function, and you should then be presented with a successful result, showing that your test path (
/top/about
in my case) has been appended withindex.html
- We now need to Publish the function for use. Head to the Publish tab, and select Publish Function. This simply results in a “Success” message at the top of the screen.
- The final step is to now associate the function with the relevant Cloudfront distributions caches, so still in the Publish Tab, click Add association, and select the relevant distribution, leave Event type as “Viewer Request”, and then select the applicable Cache behaviours to associate the function with, then click Add association
And that’s it! Once the Cloudfront Distribution has been updated, your new function will begin invocations whenever a site link that previously ended with a /
is called.
comments powered by Disqus