Created
August 9, 2018 17:06
-
-
Save kurtroberts/ae7a50083bf4373d62b27a74e953a6d2 to your computer and use it in GitHub Desktop.
Handling HTTP/HTTPS redirection in a Lambda function
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'; | |
/**** | |
Set up as a lambda function, it doesn't need any special permissions. | |
To test, you'll use a CloudFrontHTTPRedirect template. | |
Then, you'll create a CloudFront Distribution and attach this as a behavior. | |
Use the Event Type "ViewerRequest" to trigger it. | |
****/ | |
exports.handler = (event, context, callback) => { | |
/* | |
* Generate HTTP redirect response with 301 status code and Location header. | |
*/ | |
const request = event.Records[0].cf.request; | |
// get the original URL path | |
const path = request.uri | |
// set the new URL to redirect to | |
const baseURI = 'https://example.com' | |
// construct the response | |
const response = { | |
status: '301', | |
statusDescription: 'Found', | |
headers: { | |
location: [{ | |
key: 'Location', | |
value: baseURI, | |
}], | |
}, | |
}; | |
// Configure the URL redirects by building a new location | |
//value using baseURI and path | |
if (!path.match(/^\/wiki/)) | |
response.headers.location[0].value = baseURI + '/wiki' + path; | |
else | |
response.headers.location[0].value = baseURI + path; | |
callback(null, response); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment