API Gateway/Cloudfront redirects folder access from express app which will return the index.html


I have a serverless app running fine on API Gateway and CloudFront using express. The problem occurs when accessing a folder with an index.html file - it gets redirected to itself in a loop.

Main app working fine here: https://d2x40omue01gmu.cloudfront.net/

Click on blog link in header and it should eventually go to: https://d2x40omue01gmu.cloudfront.net/blog/

But it gets redirected back to itself. This is a CloudFront for an API Gateway endpoint

The express app handles GET on /blog* by returning express.static(browserFolder, { maxAge: '1m' }))

This works fine locally and on Firebase serverless: https://www.findrvparks.com/blog/

Any help appreciated

2 Answers
Accepted Answer

Turns out that running the express app on API Gateway in a subfolder means I have to add the /prod prefix to the express get handler as /prod/blog*

answered 3 months ago

Your API Gateway is returning 301 redirects on requests for /blog to /blog/

Requests for /blog/ result in a 403 which I believe is the correct behavior. However, this isn't the case for (eg) /maps - that just returns a 403 immediately, not a redirect to /maps/

I think the problem is that CloudFront has cached the 301 response for /blog and is serving it for subsequent requests for /blog/

To solve this, the best option would be to remove the direct from /blog to /blog/ if possible. Once you've done that, you'll need to invalidate /blog in the CloudFront cache.

answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions