Last active
May 28, 2021 16:39
-
-
Save jwerre/6b62d66f9083e74568982245946af127 to your computer and use it in GitHub Desktop.
Lambda@Edge Origin Request Event Handler - www to non-www permanent redirect
This file contains hidden or 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
'use strict'; | |
// Since you may want to have other redirects in the handler this | |
// function will simplify it a bit. | |
function redirect (url) { | |
return Promise.resolve({ | |
body: '', | |
status: '301', | |
statusDescription: 'Permanently moved', | |
headers: { | |
location: [{ | |
key: 'Location', | |
value: url | |
}] | |
} | |
}); | |
}; | |
// Export the event handler. | |
exports.handler = (event, context) => { | |
// Log every request. | |
console.log( JSON.stringify(event) ); | |
let request, | |
host, | |
query = '' | |
// Get the request data from the event. | |
request = event.Records[0].cf.request; | |
// Get the host header. | |
host = request.headers.host[0].value; | |
// Make sure you're passing back the query string if there is one. | |
if( 'querystring' in request && request.querystring.length) { | |
query = '?'+request.querystring; | |
} | |
// Redirect www to non-www. | |
if( host && host.length && host.startsWith('www.') ) { | |
return redirect( `https://${host.replace('www.', '')}${request.uri}${query}` ); | |
} | |
// The Host header has been whitelisted so that it's passed in with this request. | |
// If there is no redirect make sure the host header value is set back the the S3 bucket | |
// so CloudFront know where to get your html file. | |
request.headers['host'] = [{ key: 'host', value: request.origin.s3.domainName }]; | |
// Return request to CloudFront | |
return Promise.resolve(request); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If your trying to create a redirect from non-www to www replace line 42 though 44 with this: