Skip to content

Instantly share code, notes, and snippets.

@Glutnix
Created February 4, 2019 21:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Glutnix/2cbef08224af697e9d6d205dce6f5b18 to your computer and use it in GitHub Desktop.
Save Glutnix/2cbef08224af697e9d6d205dce6f5b18 to your computer and use it in GitHub Desktop.
cloudfront lambda to redirect requests for folders to the index.html inside that folder
/*
redirect requests for folders to folders/index.html
*/
const resolveUrlEndingInSlashToIndexHtml = require('./resolve-url-ending-in-slash-to-index-html');
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event that is sent to Lambda@Edge
const { request } = event.Records[0].cf;
// Extract the URI from the request
const olduri = request.uri;
// Match any '/' that occurs at the end of a URI. Replace it with a default index
const newuri = resolveUrlEndingInSlashToIndexHtml(olduri);
// 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);
};
function resolveUrlEndingInSlashToIndexHtml(url) {
// break url into parts
const parts = url.split('/');
console.log(url, parts);
const lastPart = parts.pop();
if (lastPart === '') {
parts.push('index.html');
return parts.join('/')
}
if (lastPart.indexOf('.') === -1) {
parts.push(lastPart)
parts.push('index.html');
return parts.join('/');
}
return url;
// return url.replace(/^.*\/([^\/\.]+)\/?$/, '\/$1\/index.html')
}
module.exports = resolveUrlEndingInSlashToIndexHtml;
const resolve = require('./resolve-url-ending-in-slash-to-index-html');
test('urls ending without an extension get /index.html appended', () => {
expect(resolve('/')).toBe('/index.html');
expect(resolve('/alice')).toBe('/alice/index.html');
expect(resolve('/person/alice')).toBe('/person/alice/index.html');
expect(resolve('/share-your-story')).toBe('/share-your-story/index.html');
});
test('urls ending with trailing slashes get index.html appended', () => {
expect(resolve('/person/')).toBe('/person/index.html');
expect(resolve('/person/alice/')).toBe('/person/alice/index.html');
expect(resolve('/share-your-story/')).toBe('/share-your-story/index.html');
});
test('urls ending with extensions are untouched', () => {
expect(resolve('/index.html')).toBe('/index.html');
expect(resolve('/person/alice.html')).toBe('/person/alice.html');
expect(resolve('/person/alice/story.html')).toBe('/person/alice/story.html');
expect(resolve('/share-your-story.html')).toBe('/share-your-story.html');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment