Skip to content

Instantly share code, notes, and snippets.

@michimani
Last active May 6, 2021 22:04
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/d34152f1a2b1ed4333b4f9b01d6d5297 to your computer and use it in GitHub Desktop.
Save michimani/d34152f1a2b1ed4333b4f9b01d6d5297 to your computer and use it in GitHub Desktop.
Optimizing request URI for CloudFront with Lambda@Edge that has HUGO site as origin.
'use strict';
exports.handler = (event, context, callback) => {
const host = '<REPLARE_TO_YOUR_HOST>'; // e.g. https://michimani.net
// Extract the request from the CloudFront event that is sent to Lambda@Edge
var request = event.Records[0].cf.request;
// Extract the URI from the request
var requestUri = request.uri;
// Do not anything when requesting to top page
if (requestUri == '' || requestUri == '/') {
callback(null, 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)$/)) {
const redirectUrl = host + requestUri.replace('/index.html', '') + '/';
const response = {
status: '301',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: redirectUrl,
}],
},
}
// return response to redirect (for viewer)
callback(null, response);
};
// Match any '/' that occurs at the end of a URI. Replace it with a default index
const actualUri = requestUri.replace(/\/$/, '\/index.html');
console.log('request URI: ' + requestUri);
console.log('actual URI: ' + actualUri);
// Replace the received URI with the URI that includes the index page
request.uri = actualUri;
// Return to CloudFront (for origin)
callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment