Search code examples
amazon-web-servicesaws-lambdaamazon-cloudfront

CloudFront cache, can "request.uri" be part of the cache key?


I have read the cache key documentation on cloudfront:

https://aws.amazon.com/blogs/networking-and-content-delivery/amazon-cloudfront-announces-cache-and-origin-request-policies/

I have a lambda@edge function that gets triggered by Viewer Request. There I set request.uri to values I need to fetch proper files from S3.

From the documentation I don't see anything about request.uri being part of what the cache key considers.

Is there a way to make request.uri affect the cache key?


Solution

  • In Lambda@Edge, request.uri (where the request object is event.Records[0].cf.request) is the resource (path) component of the request URL, including the filename and extension.

    This is always part of the cache key. This is default behavior and can't be disabled.

    By default, [the cache key] consists of the CloudFront distribution hostname and the resource portion of the request URL (path, file name, and extension)

    https://aws.amazon.com/blogs/networking-and-content-delivery/amazon-cloudfront-announces-cache-and-origin-request-policies/

    ...however, this isn't the complete answer.

    The value of request.uri can be modified by viewer request and/or origin request triggers... so an important consideration here is when is this value evaluated for determining the cache key?

    If the trigger is a viewer request trigger, the cache key uses the value of request.uri as it stands after the trigger runs. This means if a viewer request trigger modifies the value of request.uri (and returns the modified request object to CloudFront) then the cache key is modified to contain the revised value. Cache lookup occurs immediately after the viewer request trigger finishes and returns control to CloudFront.

    Things are very different in an origin request trigger. Modifying request.uri in an origin request trigger does not change the cache key (which is completely frozen at that point, as the cache has already been checked and a cacheable response will be stored under the same cache key that generated the cache miss). The value as it stands before the origin request trigger runs is what's in the cache key.

    Changing request.uri in either trigger type will also change the request URI that the origin server receives.