Skip to content

Instantly share code, notes, and snippets.

@michimani
Created May 6, 2021 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michimani/96703e882f07dd1173c9f682040740c2 to your computer and use it in GitHub Desktop.
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.
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