Search code examples
amazon-web-serviceshttpaws-api-gatewayamazon-cloudfrontcontent-negotiation

How to serve compressed content without caching in AWS Cloudfront with API Gateway origin?


I'm using Cloudfront distribution with Regional API Gateway origin. For endpoints, for which I can't use caching, I still need the response body to be compressed, if request includes "Accept-Encoding" header.

That's such a trivial requirement, and I think I have tried everything:

  • "Fake" caching policy with TTL=0 doesn't allow compression to be turned on.
  • API Gateway compression doesn't work without Accept-Encoding header passed, and Cloudfront never allows to pass it.
  • Origin request policy doesn't allow to pass custom Accept-Encoding header.
  • Origin request policy with "All viewer headers" doesn't work, because API Gateway doesn't like the Host header. Setting up custom domain is not working together with Cloudfront using same domain.
  • Origin doesn't allow to add custom Accept-Encoding header.

Well, after trying everything, I already expect that's not possible for a reason. But I don't understand why.

Please, explain me, what's so bad in compressing non-cached responses?

Or is there a chance I can do this?

UPD

Cloufront functions are not allowed with origin requests

In Lambda@Edge functions Accept-Encoding is read-only.


Solution

  • You have to enable caching but you could set a low TTL of 1 second and then add a header like X-Amz-Cf-Id to your cache policy to act like a cache buster. Since the value of X-Amz-Cf-Id is unique to each request it will effectively disable caching.

    CloudFront adds the X-Amz-Cf-Id header to the viewer request before forwarding the request to your origin. The header value contains an encrypted string that uniquely identifies the request.