Deployed Nextjs 13 on ec2 using Cloudfront and SSL on a custom domain, and could not connect to my app. Here's how I fixed it:

34 views Asked by At

Posting this in case someone else is having similar troubles

So I have my route 53 set with two aliased A records pointing to my cloudfront's domain, as well as two aliased AAAA ones. It has my domain and it's www counterpart listed as alternates. My origin is set to my ec2, while the behavior's "Origin or origin group" setting is set to my domain. I have both behavior and origin set to HTTPS only, though I've tried different combinations of HTTP and HTTP -> HTTPS and nothing worked. My ec2 has appropriate security groups with anywhere access on ports 80 and 443. My ec2 is running and the app worked great, so long as I connected to it using its ipv4 address and it's port number, 443, on HTTP. I troubleshot this for 2 days and nothing I'd done made any appreciable difference. I've watched YouTube tutorials, scoured through threads on this site, as well as many others, and nothing. However, I decided to try switching my cloudfront's origin and behavior settings to http only, and changing the behavior's caching behavior to legacy, and selecting all headers in the drop down just to see if that would at least give me a different error and it ended up working. So far, I've gathered the reason for this involves the https protocol blocking the communication between the resources in my vpc, even though each resource with security groups was properly configured to recieve https traffic over 443. I am investigating this further, but if anyone reading this has greater insight, I'd love to learn more.

1

There are 1 answers

0
Halod On

The error from CloudFront usually helps in root cause. In this case, I think that the issue is with the certificate used on the EC2 instance. It need to satisfy below when using with CloudFront:

  1. Certificate should be issued by a well known CA. i.e. CloudFront performs certificate verification/validation. Testing this is simple and can be done by using the domain name of your origin (the one you have used as Origin domain in CloudFront) and access it over a browser using https. If you are not getting a certificate error, it is good to go (Unless you have tinkered your trusted certificates on your laptop ;) )

  2. The Common Name or SAN entries in the certificate in EC2 instance should match either

  • that of the Origin domain
  • If you are forwarding host header to origin, then the certificate is accepted if that is found in certificate

Ref Link

Most of the times the error is at step 2 where CloudFront will reach out to Origin and is getting a certificate that is not in the "accepted" ones. This will lead to a 502 error in CloudFront. The above aws document link mentions the certificate part as a warning note.

Once the above certificate part is taken care of, you can set it back to HTTP/HTTPS or HTTPS-Only in Origin policy.