I'm having trouble setting up an easy example using Cloudfront@Edge functions for changing the custom origin of a request, while keeping the domain name.
Following this guide and this stackoverflow question I have the following setup:
custom-us.us-west-1.elb.amazonaws.com
custom-eu.eu-central-1.elb.amazonaws.com
mydistr.cloudfront.net
) with 1 origin, as done in the guide. My origin for the default behavior is custom-us.us-west-1.elb.amazonaws.com
. The cache policy is Managed-CachingDisabled
.origin-request
trigger) with the following code:'use strict';
module.exports.dynamic_routing = (event, context, callback) => {
const request = event.Records[0].cf.request;
const originUSA = "custom-us.us-west-1.elb.amazonaws.com";
const originEU = "custom-eu.eu-central-1.elb.amazonaws.com";
var destDomain = originUSA;
const custom_header = request.headers['custom-header-value'];
if (custom_header && custom_header.value == "DE") {
destDomain = originEU;
}
request.origin = {
custom: {
domainName: destDomain,
port: 80,
protocol: 'http',
path: request.uri,
readTimeout: 20,
keepaliveTimeout: 5,
customHeaders: {}
}
};
request.headers['host'] = [{ key: 'host', value: destDomain}];
callback(null, request);
};
I can correctly navigate to both Load Balancers and see the right content, which proves that the load balancers + respective lambda functions are correctly setup.
If I navigate to mydistr.cloudfront.net
the "USA" content is shown, which is correct. However, if send a request with Curl/Postman including my custom-header-value: DE
, I keep seeing the USA info:
when I expected to have changed the origin.
What am I missing?
Well...the solution was quite simple.
All the headers are arrays and thus the problem was here: custom_header.value == "DE"
where it should in fact be custom_header[0].value == "DE"
.