Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a 301 redirect loop when putting a CloudFront in front of AWS Amplify?

Background

We would like to have a CloudFront act as a router in front of our AWS Amplify SPA. The reason for this is that we need to share a common domain across all of our SPAs so we can share localStorage. Thus each SPA will be hosted at a sub-path on the CloudFront. The reason we are using Amplify is because we are using a client side routing, so we need to redirect requests from https://spaOne-amplify.com/spaOne/pages/somePage to the index.html

The basic idea is that we will have a CloudFront that proxies/caches all requests from https://cloudFrontDomain.com/spaOne/* to https://spaOne-amplify.com/spaOne/*.

Problem

However, for some reason when a SPA hosted by Amplify receives a Via header that looks like it came from a CloudFront, it goes into a redirect loop.

  • GET https://spaOne-amplify.com/spaOne
  • 301 - /someRandomId/
  • GET https://spaOne-amplify.com/someRandomId
  • 301 - /someRandomId/
  • ... and so on and so forth

I can't find any mention of this behaviour detailed anywhere, and I'm at a loss for how to avoid it. If I remove the Via header, or change it, the behaviour stops. The following causes a redirect loop:

  • Via: 1.1 7331c3ff7c4cd86239addbfddaa5cee4.cloudfront.net (CloudFront)
  • Via: 1.1 abc.cloudfront.net (CloudFront)

But these do not:

  • Via: 1.1 7331c3ff7c4cd86239addbfddaa5cee4.cloudfront.net
  • Via: 1.1 spaOne-amplify.com (CloudFront)
like image 473
Digital Deception Avatar asked Nov 07 '22 05:11

Digital Deception


1 Answers

So the idea here it's to use target group to load distribution (or redirect rules for your network). And by default, I'm not sure there is a way at all, to do it within CloudFront.

  1. However the way it could be done, by creating Load Balancer (application in your case) and then in your CloudFront instance specify origin to be your load balancer.

  2. Once all the content is going trow the Load Balancer, you can create Target Groups with your redirects behavior to one or another source.

like image 123
GensaGames Avatar answered Nov 14 '22 06:11

GensaGames