Search code examples
phphttp-redirectamazon-s3s3-rewrite-rules

Amazon S3 rewrite rules redirection issue


We use Amazon S3 storage to host images and its thumbnails. We upload new images without its thumbnails to generate it on demand. To do it, we use S3 rewrite rules which look like this:

<RoutingRules>
    <RoutingRule>
        <Condition>
           <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>mysite.com</HostName>
            <ReplaceKeyPrefixWith>/path/to/thumbnail/generator.php?image=</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

If a thumbnail doesn't exist yet, it will be redirected to our script, which generates a new thumbnail, uploads to S3 and sends it in a response. The script works fine and does what we need. The problem is that all next calls to the newly generated thumbnails are redirected to the script again and again event if a thumbnail is already available in the S3 bucket...

How can I stop "next redirects"?


Solution

  • The default http status returned by routing rules in S3 appears to be 301 Moved Permanently. When this code is seen, the browser is supposed to use the new location for subsequent requests... so the behavior you are seeing is not entirely unexpected, in light of that.

    A "temporary" redirect such as the one you are doing should instead return 302 Found (technically, 302 is the only part that matters, some implementations will use 302 Moved Temporarily or another message). With such a redirect, browsers are supposed to send future requests to the original location.

    Using <HttpRedirectCode> to override the default value should be what is necessary to get the intended behavior.

    <Redirect>
      <HttpRedirectCode>302</HttpRedirectCode>
      <HostName>example.com</HostName>
      <ReplaceKeyPrefixWith>/path/to/thumbnail/generator.php?image=</ReplaceKeyPrefixWith>
    </Redirect>