Skip to content

Instantly share code, notes, and snippets.

@jwerre
Last active May 28, 2021 16:39
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 jwerre/6b62d66f9083e74568982245946af127 to your computer and use it in GitHub Desktop.
Save jwerre/6b62d66f9083e74568982245946af127 to your computer and use it in GitHub Desktop.
Lambda@Edge Origin Request Event Handler - www to non-www permanent redirect
'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);
};
@jwerre
Copy link
Author

jwerre commented May 28, 2021

If your trying to create a redirect from non-www to www replace line 42 though 44 with this:

if( host && host.length && !host.startsWith('www.') ) {
    return redirect( `https://${'www.'}${request.uri}${query}` );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment