Created
July 6, 2018 04:30
-
-
Save ravituvar/e60ca1ae8c7dca0245d8b1ed303a03e0 to your computer and use it in GitHub Desktop.
Redirect to index.html pages in subdirectories when hosting Static html on S3 and Distributed via cloudfront
This file contains hidden or 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'; | |
exports.handler = (event, context, callback) => { | |
function getFileExtension(filename) { | |
return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2); | |
} | |
// Extract the request from the CloudFront event that is sent to Lambda@Edge | |
var request = event.Records[0].cf.request; | |
var extension = getFileExtension(request.uri.substr(request.uri.lastIndexOf('/') + 1)); | |
console.log(extension); | |
// Extract the URI from the request | |
var olduri = request.uri.replace('www.',''); | |
// Match any '/' that occurs at the end of a URI. Replace it with a default index | |
var newuri = olduri.replace(/\/$/, '\/index.html'); | |
if(extension=='' && extension!=='html' && extension!=='htm'){ | |
newuri = request.uri.replace('www.','') + '/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