Skip to content

Instantly share code, notes, and snippets.

@zahna
Created October 16, 2019 18:38
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 zahna/d0a4b74ba332109c1dbd1ac4dd6c0215 to your computer and use it in GitHub Desktop.
Save zahna/d0a4b74ba332109c1dbd1ac4dd6c0215 to your computer and use it in GitHub Desktop.
Lambda@Edge to rewrite Host: header in Cloudfront based on client IP address
// https://gist.github.com/prenagha/886c44526c7e9b1bc9e904900687f6b0
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html
'use strict';
exports.handler = (event, context, callback) => {
let request = event.Records[0].cf.request;
if (request['clientIp'].match(/^[456]/)) {
request.headers['x-client-ip-match'] = [{'key': 'X-Client-IP-Match', 'value': 'true'}];
request.headers['host'] = [{'key': 'Host', 'value': 'www2.zahna.com'}];
} else {
request.headers['x-client-ip-match'] = [{'key': 'X-Client-IP-Match', 'value': 'false'}];
request.headers['host'] = [{'key': 'Host', 'value': 'www.zahna.com'}];
}
request.headers['x-client-ip'] = [{'key': 'X-Client-IP', 'value': request['clientIp']}];
callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment