Created
May 6, 2021 22:10
-
-
Save michimani/96703e882f07dd1173c9f682040740c2 to your computer and use it in GitHub Desktop.
Optimizing request URI for CloudFront with CloudFront Functions (CF2) that has HUGO site that deployed to a S3 bucket as origin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function handler(event) { | |
var host = '<REPLARE_TO_YOUR_HOST>'; // e.g. https://michimani.net | |
var request = event.request; | |
var requestUri = request.uri; | |
// do not anything when requesting to top page | |
if (requestUri == '' || requestUri == '/') { | |
return request; | |
} | |
// redirect to URI end with '/' if URL end with 'index.html' or not '/' | |
if (requestUri.match(/((page|post|posts|tags|categories|archives|about)(\/.*[^\/])?|\/index\.html)$/)) { | |
var redirectUrl = host + requestUri.replace('/index.html', '') + '/'; | |
var response = { | |
statusCode: 301, | |
statusDescription: 'Found', | |
headers: { | |
location: { | |
value: redirectUrl | |
} | |
} | |
} | |
// response to viewer | |
return response; | |
} | |
// complete `index.html` for requests to origin | |
var actualUri = requestUri.replace(/\/$/, '\/index.html'); | |
request.uri = actualUri; | |
// request to origin | |
return request; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment