I created a Cloudfront distribution in front of an S3 bucket with a RoutingRule to redirect to a lambda function if the requested file is not found. I´m using this to resize images.
Desired flow:
- Request the file to Cloudfront
- File not found in Cloudfront check S3
- File not found in S3 redirect to the lambda function
- Lambda will find the original file, resize it and redirect back to the Cloudfront url.
Redirect rule set on s3 website:
<RoutingRules>
<RoutingRule>
<Condition>
<KeyPrefixEquals/>
<HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
</Condition>
<Redirect>
<Protocol>https</Protocol>
<HostName>mylambda.execute-api.us-east-1.amazonaws.com</HostName>
<ReplaceKeyPrefixWith>/?key=</ReplaceKeyPrefixWith>
<HttpRedirectCode>307</HttpRedirectCode>
</Redirect>
</RoutingRule>
</RoutingRules>
I´m having a problem with the step 4 when the lambda function redirects back to the original url Cloudfront cached the 404? and the routing rule from S3 is redirecting again to the lambda function causing a loop.
- I confirmed that the lambda function generated the file.
- if I invalidate the file on Cloudfront I successfully see it served from S3)
I tried adding a 0 TTL to the 404 error page but didn´t help.
the redirect rule returns a 307 status code [Temporary Redirect]. But I don´t know how to set a 0 TTL on this. I couldn´t find the option on the Cloudfront custom error response page.
According to this article. the 307 is cached. need to set a rule for it... somewhere .
This is a follow up question on RoutingRules on AWS S3 Static website hosting
I appreciate your help.
Update: 1. Removed the RoutingRule on S3 2. Added a new origin to the Cloudfront distribution (API gateway)
the lambda function now returns
return {
statusCode: "200",
body: "image converted",
};
Checking Cloudwatch logs I don´t see the lambda function getting invoked and when I go to https://myCloudfront.cloudfront.net/photos/resized/test.jpg
I only see a plain 404
I also added a custom error page with a 0 TTL for 404
the good news is if I go to the api gateway passing key=/photos/resized/test.jpg and then go to https://my.cloudfront.net/photos/resized/test.jpg it works. it reads the image correctly.
I think the problem is with the failover that´s not triggering the api gateway call.




