2
votes

I have some problem on invalidating the cache of my CloudFront distribution.

I mapped a wildcard domain name to my CloudFront distribution; then I created a Lamba@Edge that modify the request origin redirecting each subdomain to its subfolder.

It works in this way:

aaa.mydomain.com => mydomain.com/aaa
bbb.mydomain.com => mydomain.com/bbb
ccc.mydomain.com => mydomain.com/ccc
...

I'm not be able to invalidate the cache: if I invalidate the path /bbb/* it doesn't work. Instead with the path /* works, but in this way I invalidate all the S3 Bucket and I would like to avoid it.

Any help?

Thanks!

2

2 Answers

1
votes

I believe you're using origin request Lambda function currently and It doesn't include the changed path to cache key, I know viewer request would help in achieving it but unfortunately then you need to write viewer request (change path) and origin request to choose origin.

1
votes

I ran into the same problem. At first I investigated writing a Lambda@Edge function that would check to see if content should be invalidated and then break the cache by appending a query parameter to the URL. But this seemed to be just as problematic (and expensive) as invalidating the entire S3 bucket. The solution I settled on instead was using the Cache-Control: no-cache header on the specific assets that shouldn't be cached by CloudFront and then just invalidating the other cached assets with query parameters. And this method doesn't require issuing any CloudFront invalidations.

So for example, if I'm hosting a static site on CloudFront / S3 that looks like this:

- index.html
- header.jpg
- site.css

I upload it to S3 as follows:

- index.html // Cache-Control: no-cache
- header.jpg // Linked with <img src='header.jpg?uniquedigest' />
- site.css // Linked with <link href='site.css?uniquedigest' />

This way everything is kept up to date in CloudFrontL Only the index.html isn't cached and all the assets are still cached after the initial fetch from the origin S3 bucket. The one downside is that the index.html is always fetched from origin but HTML should be small enough that this doesn't have a big performance impact.