Search code examples
amazon-web-servicesamazon-cloudfrontaws-lambda-edgecloudfront-functions

How to Configure AWS CloudFront to Cache Responses Based on Host Header Value?


I'm currently using AWS CloudFront to distribute requests to an Application Load Balancer (ALB), which then forwards them to EC2 instances. I need to configure caching based on the Host header value. Specifically:

If the Host header is api.domain.com, I don't want CloudFront to cache the response at all.

If the Host header is web.domain.com, I want CloudFront to cache the response for 24 hours.

I understand that I need to use cache behaviors and cache policies, but I’m not sure how to set them up correctly to achieve the desired caching behavior based on the Host header value.

Do i need to modify cache-control headers using CloudFront-function/lambda-edge-function if so how to do so.


Solution

  • If you're using 2 different domains I see these 2 options:

    1. Using two different distribution

    The easies way is to create a new distribution for each domain

    2. Modify Cache-Control with Lambda@Edge

    If you still want to use one distribution you might want to add flexibility by writing a custom Lambda@Edge and attach it to the Viewer request

    Here is an example of the Lambda code:

    'use strict';
    exports.handler = (event, context, callback) => {
       const request = event.Records[0].cf.request;
       const headers = request.headers;
       if (headers.host[0].value === 'api.domain.com') {
           request.headers['cache-control'] = [{ key: 'Cache-Control', value: 'no-cache, no-store, must-revalidate' }];
       } else if (headers.host[0].value === 'web.domain.com') {
           request.headers['cache-control'] = [{ key: 'Cache-Control', value: 'max-age=86400' }];
       }
       callback(null, request);
    };