Created
February 28, 2023 15:03
-
-
Save leggiero/fae284b31d64d01f0accb93fb8286e50 to your computer and use it in GitHub Desktop.
CloudFront Function to redirect other domains
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
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