Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CloudFront Function for routing request to origin based on HTTP Header

I am trying to implement a solution based on routing the request to a specific origin based on HTTP header on the request.

We are using CloudFront for caching, and we have attached 2 ALBs as origin. Now when the HTTP header has an old value, it should hit ALB1, and when the request header has a new value set, then it should hit ALB2.

Still deciding the plan.

like image 509
Nauti Avatar asked Sep 20 '25 08:09

Nauti


1 Answers

CloudFront has two types of edge compute: CloudFront Functions and Lambda@Edge. CloudFront functions only supports viewer-facing (request/response) events, while Lambda@Edge supports both viewer-facing (request/response) and origin-facing (request/response).

Because you want to dynamically change the origin (host) that CloudFront routes the request to, you need to use an origin-request event. That means you'll need Lambda@Edge.

The process to do so is straightforward:

  1. Ensure the HTTP header that this solution is predicated on is either in your cache policy (if part of your cache key) or origin request policy (if not part of your cache key). This will instruct CloudFront to make the viewer header available to your Lambda@Edge function.
  2. Write a Lambda@Edge function that conditionally checks the header, and updates the host header of the request to either ALB1 or ALB2. CloudFront will use that host to make the request to your origin.

Example here — https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-routing-examples

like image 96
Cristian Avatar answered Sep 22 '25 06:09

Cristian