Created
April 17, 2018 16:33
-
-
Save karolmajta/6aad229b415be43f5e0ec519b144c26e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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