I want to use different origins according to the relative paths of my website.
My root domain is example.com and it should be served with example01.cloudfront.net and example.com/pathxx/ should be served with example02.cloudfront.net. These two CloudFront distributions are linked to two s3 buckets with static sites.
I have mapped the example.com to another CloudFront distribution. Following is the code I'm using at the Lambda@Edge on that Cloudfront distribution's origin-request trigger.
exports.handler = async (event, context, callback) => {
var request = event.Records[0].cf.request;
let domain = "";
if (request.uri.match(/\/pathxx\//)) {
domain = "example02.cloudfront.net";
request.uri = request.uri.replace(/\/pathxx\//,"/");
} else {
domain = "example01.cloudfront.net";
}
request.origin = {
custom: {
domainName: domain,
port: 80,
protocol: "http",
path: "",
sslProtocols: ["TLSv1", "TLSv1.1"],
readTimeout: 5,
keepaliveTimeout: 5,
customHeaders: {}
}
};
request.headers["host"] = [{ key: "host", value: domain }];
callback(null, request);
};
When I used this code and enter example.com on the browser then it redirects to the example01.cloudfront.net and example.com/pathxx redirects to the example02.cloudfront.net by receiving 301 status codes.
But if I change the CloudFront origins to their s3 bucket URLs then this redirection doesn't occur and I will see my example.com domain always as I'm expecting and I will not receive any 301 codes which causes redirects.
...
if (request.uri.match(/\/pathxx\//)) {
domain = "example02.s3.amazonaws.com";
request.uri = request.uri.replace(/\/pathxx\//,"/");
} else {
domain = "example01.s3.amazonaws.com";
}
...
Is that means we can't use CloudFront distribution domains as custom origins??
Due to caching issues, I must use CloudFront domains for the custom origins therefore I cannot use s3 bucket URLs. This is a limitation on my project's architecture and also using CloudFront domains meant to achieve pre-caching also.