Skip to content

Instantly share code, notes, and snippets.

@kurtroberts
Created August 9, 2018 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtroberts/ae7a50083bf4373d62b27a74e953a6d2 to your computer and use it in GitHub Desktop.
Save kurtroberts/ae7a50083bf4373d62b27a74e953a6d2 to your computer and use it in GitHub Desktop.
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