Created
April 23, 2017 15:18
-
-
Save evanderkoogh/f9012bc0163b6d9f2bde49046d8cf720 to your computer and use it in GitHub Desktop.
Example Edge@Lambda in AWS Cloudfront. Change URI based on host header
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'; | |
/* | |
* HTTP headers are case-insensitive. So 'Host' is a valid header, but so | |
* is 'host' or 'hOst'. To make sure we don't miss a header we first lowerCase | |
* all of them and then check for the lowercase version of the header | |
*/ | |
const normaliseHeaders = (headers) => { | |
const normalisedHeaders = {}; | |
const fields = Object.keys(headers); | |
for(let i = 0, len = fields.length; i < len; i++ ) { | |
normalisedHeaders[fields[i].toLowerCase()] = headers[fields[i]]; | |
} | |
return normalisedHeaders; | |
}; | |
/* | |
* We have all static assets for all of our customers in one S3 Bucket | |
* but in separate folders. If people come through the linc-app.co domain | |
* we need to prepend their sitename to the URI so Cloudfront can find | |
* the assets in the S3 Bucket. | |
* So: https://myreactapp.linc-app.co/_assets/js/main.abcde.js becomes | |
* /myreactapp.linc-app.co/_assets/js/main.abcde.js when looking up the | |
* file in S3. | |
*/ | |
exports.handler = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
const headers = normaliseHeaders(request.headers); | |
const host = Array.isArray(headers.host) ? headers.host[0] : headers.host; | |
if(host) { | |
const subdomains = host.split('.'); | |
if(subdomains && subdomains[0]) { | |
request.uri = `/${subdomains[0]}${request.uri}`; | |
return callback(null, request); | |
} | |
} | |
console.log(`Couldn't find a suitable Host header: ${host}`); | |
callback("Couldn't find a suitable Host header"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment