Skip to content

Instantly share code, notes, and snippets.

@karolmajta
Created April 17, 2018 16:33
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save karolmajta/6aad229b415be43f5e0ec519b144c26e to your computer and use it in GitHub Desktop.
Save karolmajta/6aad229b415be43f5e0ec519b144c26e to your computer and use it in GitHub Desktop.
'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