Skip to content

Instantly share code, notes, and snippets.

@dave-malone
Last active May 14, 2018 13:41
Show Gist options
  • Save dave-malone/1c49446b1c945b05a40b7b71c67eb7e6 to your computer and use it in GitHub Desktop.
Save dave-malone/1c49446b1c945b05a40b7b71c67eb7e6 to your computer and use it in GitHub Desktop.
'use strict'
/* This list may be incomplete or outdated! It may be best to integrate with an external service to obtain these values */
const eu_country_codes = ['BE','BG','CZ','DK','DE','EE','IE','EL','ES','FR','HR','IT','CY','LV','LT','LU','HU','MT','NL','AT','PL','PT','RO','SI','SK','FI','SE','UK']
const us_origin_domain = 'ec2-54-166-49-18.compute-1.amazonaws.com'
const eu_origin_domain = 'ec2-34-244-9-66.eu-west-1.compute.amazonaws.com'
/* This is an origin request function */
exports.handler = (event, context, callback) => {
console.log(`edge-router processing request:\n${JSON.stringify(event, null, 2)}`)
if(!request.origin.custom){
return callback(`Request did not contain a custom origin: ${JSON.stringify(event, null, 2)}`)
}
const request = event.Records[0].cf.request
const headers = request.headers
/*
* Based on the value of the CloudFront-Viewer-Country header, direct the user to a regional origin.
* NOTE: 1. You must configure your distribution to cache based on the
* CloudFront-Viewer-Country header. For more information, see
* http://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers
* 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer
* request event. To use this example, you must create a trigger for the
* origin request event.
*/
if (headers['cloudfront-viewer-country']) {
const countryCode = headers['cloudfront-viewer-country'][0].value
console.log(`cloudfront-viewer-country: ${countryCode}`)
request.origin.custom.domainName = us_origin_domain
if(eu_country_codes.includes(countryCode)){
console.log(`EU country code detected`)
request.origin.custom.domainName = eu_origin_domain
}
console.log(`modified request:\n${JSON.stringify(request, null, 2)}`)
}
callback(null, request)
}
@dave-malone
Copy link
Author

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