Skip to content

Instantly share code, notes, and snippets.

@leggiero
Created February 28, 2023 15:03
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 leggiero/fae284b31d64d01f0accb93fb8286e50 to your computer and use it in GitHub Desktop.
Save leggiero/fae284b31d64d01f0accb93fb8286e50 to your computer and use it in GitHub Desktop.
CloudFront Function to redirect other domains
var domain = 'example.com';
function handler(event) {
// console.log('Event:\n' + JSON.stringify(event, null, 2));
// console.log('Request:\n' + JSON.stringify(event.request, null, 2));
var request = event.request;
var uriQs = request.uri + (!!Object.keys(request.querystring).length ? '?' + querystringText(request.querystring) : '');
var url = request.headers.host.value + uriQs;
if (request.headers.host.value === domain) {
console.log(`Passthrough: ${url}`);
return request;
}
var location = 'https://' + domain + uriQs;
console.log(`Redirect: ${url} to ${location}`);
return {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
'location': {
value: location,
},
},
};
};
function querystringText(querystring) {
var text = '';
for (var key in querystring) {
if (text !== '') {
text += '&';
}
text += encodeURIComponent(key) + '=' + encodeURIComponent(querystring[key].value);
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment