Skip to content

Instantly share code, notes, and snippets.

@maguzzi
Created December 9, 2023 17:29
Show Gist options
  • Save maguzzi/d53ccafd12c693471aaacf84d183368b to your computer and use it in GitHub Desktop.
Save maguzzi/d53ccafd12c693471aaacf84d183368b to your computer and use it in GitHub Desktop.
Lambda@Edge for 301 redirect
export const handler = async (event, context, callback) => {
var olduri = event.Records[0].cf.request.uri; // search for the uri in cloudfront request
var host = event.Records[0].cf.request.headers.host.find(o => o.key === 'Host').value; // search for the host in the key-value headers
if (host.startsWith("www.")) {
const response = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
location: [{
key: 'Location',
value: "https://"+host.replace("www\.","")+olduri // append also olduri, so that also internal pages are redirected
}]
}
};
callback(null, response); // fire the redirect
} else {
// maybe a URL rewrite here
}
}
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment