Skip to content

Instantly share code, notes, and snippets.

@prenagha
Created September 2, 2019 15:45
Show Gist options
  • Save prenagha/7f025cd1b491db17cc4eddccf7cbc23f to your computer and use it in GitHub Desktop.
Save prenagha/7f025cd1b491db17cc4eddccf7cbc23f to your computer and use it in GitHub Desktop.
Lambda@Edge to redirect from non-canonical (example.net) to canonical (example.com)
'use strict';
/**
* Deploy this Lambda@Edge, in Origin Request event,
* to a CloudFront distribution that hosts the
* NON-Canonical domains. It will redirect everything
* to the canonical version of the URL.
* And let CloudFront and browsers cache the redirect.
*/
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const uri = request.uri;
const queryString = request.querystring;
const canonicalUrl = 'https://example.com' + uri +
(queryString ? '?' + queryString : '');
const response = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: canonicalUrl,
}],
'cache-control': [{
key: 'Cache-Control',
value: 'max-age=86400,public',
}],
},
};
callback(null, response);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment