Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'use strict';
const pointsToFile = uri => /\/[^/]+\.[^/]+$/.test(uri);
exports.handler = (event, context, callback) => {
// 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 oldUri = request.uri;
var newUri;
if (!pointsToFile(oldUri) && !oldUri.endsWith('/')) {
const newUri = request.querystring ? `${oldUri}/?${request.querystring}` : `${oldUri}/`;
return callback(null, {
body: '',
status: '301',
statusDescription: 'Moved Permanently',
headers: {
location: [{
key: 'Location',
value: newUri,
}],
}
});
} else {
newUri = oldUri;
}
// Match any '/' that occurs at the end of a URI. Replace it with a default index
newUri = newUri.replace(/\/$/, '\/index.html');
// Log the URI as received by CloudFront and the new URI to be used to fetch from origin
console.log("Old URI: " + oldUri);
console.log("New URI: " + newUri);
// Replace the received URI with the URI that includes the index page
request.uri = newUri;
// Return to CloudFront
return callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.