AWS CloudFront does not directly support multiple domain based routing similar to AWS Application Load Balancer.
However there are other options available to achieve this. To achieve multi-domain based traffic distribution similar to an Application Load Balancer (ALB) on CloudFront, you can use:
- Lambda@Edge: Write a Lambda function to inspect incoming requests and route them to different origins based on URL paths or other criteria.
- CloudFront Functions: Use CloudFront Functions (a lightweight edge computing feature) to manipulate requests and route them to different origins.
Here we will look at how to use CloudFront Functions to achieve this.
CloudFront function to route traffic based on domain name:
import cf from 'cloudfront';
function handler(event){
const request = event.request;
const headers = request.headers;
// Set default origin
const originDNS = 'xyz-123456.us-west-2.elb.amazonaws.com';
// Check if the Host header matches 'xyz.com'
if (headers.hosts && headers.host.value === 'xyz.com'){
// Set origin for xyz.com
originDNS = 'xyz-123456.us-west-2.elb.amazonaws.com';
} else if (headers.hosts && headers.host.value === 'abc.com'){
// Set origin for abc.com
originDNS = 'abc-123456.us-west-2.elb.amazonaws.com';
}
cf.updateRequestOrigin({
"domainName": originDNS
})
return request;
}
Once you have created and published the CloudFront function, associate the CloudFront function to your CloudFront distribution.
Pricing is based on number of invocations of the CloudFront function.
Invocation pricing is $0.10 per 1 million invocations ($0.0000001 per invocation).
Useful Links: