Handling HTTP/HTTPS redirection in a Lambda function
'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