Created
February 26, 2019 04:40
-
-
Save darylteo/222212e2256ce70699bcaa6875d27166 to your computer and use it in GitHub Desktop.
Origin Request Trigger for lambda@edge supporting nice-urls
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'; | |
exports.handler = (event, context, callback) => { | |
// Extract the request from the CloudFront event that is sent to Lambda@Edge | |
const request = event.Records[0].cf.request; | |
// Extract the URI from the request | |
const olduri = request.uri; | |
const [path, query] = olduri.split('?'); | |
let redirecturi = null; | |
let originuri = null; | |
if (/\/index\.html$/.test(path)) { | |
// disallow index.html suffixes | |
redirecturi = path.substring(0, path.length - 11); | |
if (redirecturi === '') { | |
redirecturi = '/' | |
} | |
} else if (/\/[^/.]+\/$/.test(path)) { | |
// if it ends in a slash, remove it | |
redirecturi = path.substring(0, path.length - 1); | |
} else if (/\/[^/.]+$/.test(path)) { | |
originuri = path + '\/index.html'; | |
} else if (path === '' || path === '/') { | |
originuri = '\/index.html'; | |
} | |
// Log the URI as received by CloudFront and the new URI to be used to fetch from origin | |
console.log("Request URI: " + olduri); | |
if (redirecturi) { | |
redirecturi += (query ? `?{query}` : '') ; | |
console.log("Redirect URI: " + redirecturi); | |
return callback(null, { | |
status: 301, | |
headers: { | |
location: [{ key: 'Location', value: redirecturi }], | |
}, | |
}); | |
} | |
if (originuri) { | |
originuri += (query ? `?{query}` : ''); | |
request.uri = originuri; | |
} | |
console.log("Origin URI: " + request.uri); | |
return callback(null, request); | |
}; |
And then add Trust Relationship
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com",
"edgelambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to add IAM permissions for your new Lambda function