I’m trying to put my apps behind the AWS cloudfront. I’ve configured my cloudfront origins to the generated fly.io URL for my app. when I want to get access to the apps via cloudfront I’ve got the below error.
502 ERROR
The request could not be satisfied.
CloudFront wasn't able to connect to the origin. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
FYI, I can reach my app via fly.io generated URL and my machines are healthy.
This is probably because CloudFront is looking for an HTTP backend, while the default behaviour for Fly.io Apps is to serve HTTPS. You probably don’t need CloudFront, we have our own DDoS protection and etc, but if you need it for something else you’ll want to configure your app to serve on HTTP and use a TCP service instead of an HTTPS one in fly.toml. See the docs here.
@omid if the “http vs. https” theory is correct, you can set force_https = false to have your app serve content over both http and https. force_https = true means that hitting your site via http will result in a 301 redirect to https.
What happens is that the viewer makes a request to my custom domain my-app.domain.com on CloudFront, and its client sets the Host header to my-app.domain.com. Therefore, in both cases, the origin server (my app on fly.io) is searching for the certificate for that domain to establish the connection. Since there is no such certificate present on either of the origin servers, the connection fails in both cases.
To fix this, I should attach the Managed-AllViewerExceptHostHeader request policy to /* routes. This instructs CloudFront to remove the original Host header value set to my-app.domain.com and replace it with the generated fly.io URL, respectively. This, in turn, allows the origin to find the correct certificate and establish the connection.
One last peculiarity is that the request policy requires me to have a cache policy set as well. For the fly.io app, in particular, it is a good idea to use the Managed-CachingDisabled cache policy.
After these changes, I’ve successfully redirected all of my traffic to my fly.io app.