Created
September 2, 2019 15:45
-
-
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)
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
'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