Created
December 9, 2023 17:29
-
-
Save maguzzi/d53ccafd12c693471aaacf84d183368b to your computer and use it in GitHub Desktop.
Lambda@Edge for 301 redirect
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
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