Search code examples
amazon-web-servicescachingamazon-cloudfrontcdncache-control

CloudFront customize object caching does not work


I've setup CloudFront with a custom origin (no S3). There custom origin is serving files with cachecontorl headers:

 curl -I https://origin-site/assets/common.css?v=12345

HTTP/1.1 200 OK
Cache-Control: max-age=86400

I've configured CloudFront to customize the MinTTL, DefaultTTL and MaxTTL.

In CloudFormation:

    CacheBehaviors:
      - TargetOriginId: !Sub 'xxx-${Environment}'
        PathPattern: "assets/*"
        ViewerProtocolPolicy: redirect-to-https
        Compress: true
        MinTTL: 0
        DefaultTTL: 30672000
        MaxTTL: 30672000
        AllowedMethods:
          - HEAD
          - GET
          - OPTIONS
        CachedMethods:
          - HEAD
          - GET
          - OPTIONS
        ForwardedValues:
          QueryString: true
          Cookies:
            Forward: none

Now I see custom settings in the console and the correct values. I've even done an invalidation after it.

Now I access the asset through the CDN:

curl -I https://cdn-cloudfront-site/assets/common.css?v=12345
HTTP/1.1 200 Connection Established
Proxy-Agent: IWSS
Date: Mon, 18 Nov 2019 13:05:29 GMT

HTTP/1.1 200 OK
Content-Type: text/css
Content-Length: 104120
Connection: keep-alive
Cache-Control: max-age=86400
Last-Modified: Fri, 15 Nov 2019 10:15:38 GMT
Accept-Ranges: bytes
ETag: "0415ea09d9bd51:0"
Server: Microsoft-IIS/10.0
X-Content-Type-Options: nosniff
Access-Control-Allow-Origin: *
Date: Mon, 18 Nov 2019 13:05:30 GMT
Vary: Accept-Encoding
X-Cache: Miss from cloudfront
Via: 1.1 b912dc97777020eb19579888add26978.cloudfront.net (CloudFront)
X-Amz-Cf-Pop: FRA50-C1
X-Amz-Cf-Id: 46wPzKf7v7A2vTbWQMRVZf2V8KCPdCtZSCdY9P82MtDLKJXe3TxskQ==

First a miss, then a hit, that's okay. But I want Cache-Control: max-age=86400 as Cache-Control: max-age=30672000 but this is not changed? What am I missing here?

UPDATE: I read:

You can use these options in many interesting ways! For example, if you don’t set any cache control header on your origin, you can use the Default TTL to specify the cache duration for the edge locations. Or, you can completely override the cache-control header set by origin by setting all three of the values (Min, Max, and Default) to the same value.

But then my origin is not checked for that whole time?


Solution

  • What you define TTLs in the CloudFront configuration is local to CloudFront to know how long do you want to cache it on CloudFront but it doesn't mean that CloudFront will add the cache-control header. CloudFront doesn't add cache-control header but it honors the header if it was set by the origin.

    CloudFront Cache Control

    Above link has a table which will give you information on how CloudFront behaves if origin has a cache-control header set and also if min,max, default TTL has been set.

    The cache-control header should be added by Origin or using Lambda@edge