Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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