Search code examples
http-redirectcachingamazon-cloudfrontbrowser-cache

What is the relationship between 3xx and caching around cloudfront?


I came across this issue and tried to get my head around caching and redirection. Base on what I read 301 and 302 http protocol, this is how I see it, a request sends to server (in this case cloudfront) and triggers a direction (base on the configuration but we assume this is default settings). In the response, the client sees a 301 or 302, which indicates the resources they get back. If the status is 301, means that the link has permanently moved, therefore new resources will return back to the client. While 302 tells the client that the resource is found and here it is, without doing any further action.

"If your origin returns a 301 or 307 status code, CloudFront doesn't follow the redirect to the new location."

From the above quote, does this mean 301/307 will return cached resource from the backend? Does Cloudfront uses a the status code for the redirection different?

I know I have too many questions within one post, but my main concern is caching and redirection. Can someone explain this relationship in a layman term? Thank you in advance

By the way, this is how I trigger my redirection:

Navigate to https://example.com/index.html

<!DOCTYPE html>
<head>
  <meta http-equiv="refresh" content="0; url=https://example.com/copy/index.html">
  <link rel="canonical" href="https://example.com/copy/index.html">
</head>

Extra notes:

Explains what we should do to manage our cache on the Cloudfront


Solution

  • "If your origin returns a 301 or 307 status code, CloudFront doesn't follow the redirect to the new location."

    Above line means that CloudFront forwards the response to the client instead of following the redirection provided by Origin.

    What It does: Client --> CloudFront --> Origin (301) <--> CloudFornt --> Client (gets new location)

    As you can see CloudFront forwards the response header (along with status code) to client and it's the client who needs to follow the redirection.

    CloudFront doesn't do: Client --> CloudFront --> Origin(301) --> CloudFront (follows 301 and makes a request to new location)-->origin

    Though CloudFront caches the 3xx response which means the next time if someone makes the same request, CloudFront serves response from it's cache.

    When CloudFront server 301/307 by his own(not from Origin): HTTP to HTTPS redirection (301 for GET, 307 for POST) or Lambda@edge configured to do so.