CloudFront error when serving over HTTPS using SNI
A kind rep by the name of Alastair@AWS from the AWS CloudFront forums solved this for me:
I have identified your CloudFront distribution and the S3 bucket acting as the origin for this distribution.
I can re-create and explain the intermittent '502 Bad Gateway' response you are receiving.
This response is returned by CloudFront when you attempt to access a URL using the HTTPS protocol that is not currently cached by CloudFront. The reason for this error is CloudFront is attempting to contact your origin using the HTTPS protocol, and this is failing.
The reason for this failure is you have configured your origin as an S3 bucket, but you are using the "Custom Origin" type and directing to the S3 website URL for this bucket. If you attempt to hit your S3 website URL using HTTPS, you will note this does not work. S3 website hosting only supports serving content using the HTTP protocol (http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff).
Now, the intermittent page load behavior you are seeing is due to CloudFront returning the pages it currently has in its cache. You should be able to re-create this scenario as follows:
- Hit a page on your site using HTTPS. You should get a '502 Bad Gateway' error back.
- Hit the same page using HTTP. You should see the page.
- Hit the page again using HTTPS. You should now get the expected result, as CF has served the content from its cache rather than attempting to contact your origin.
To resolve this issue, please try the following:
- Open the CloudFront Management Console and open your distribution.
- Navigate to the Origins tab, select your origin and click "Edit"
- Modify the "Origin Protocol Policy" to "HTTP Only".
- Save the changes and wait about 15 minutes for the change to take effect.
- Test
My expectation is this will force CloudFront to contact your origin using HTTP only. I have tested this in my environment with an S3 Website hosted bucket and I can successfully load content via both HTTP and HTTPS.
Here's the link to the original forum thread.
I had a similar issue to this and, as @Michael-sqlbot suggested, switched from custom origin to S3. That did not, by itself, resolve the issue.
In addition to switching the origin, Andrew from AWS support said that aliases work better than CNAMEs. I had been using CNAMEs. When I switched to aliases (one for IPv4 and one for IPv6) it worked. Here is the Route 53 documentation for CloudFront that shows how to setup aliases for CloudFront.