32

I'm using AWS API Gateway with a custom domain. When I try to access https://www.mydomain.com it works perfectly, but when i try http://www.mydomain.com it can't connect.

Is there a way to redirect the http -> https with the custom domain in API Gateway? If not, is there a way to get the http:// links to work just like the https:// links?

supersan
  • 4,328
  • 1
  • 34
  • 51

1 Answers1

26

API Gateway doesn't directly support http without TLS, presumably as a security feature, as well as for some practical considerations.

There is not a particularly good way to do this for APIs in general, because redirection of a POST request from HTTP to HTTPS is actually a little bit pointless -- the data is has already been sent insecurely by the time the redirect is generated, unless the client has asked the server to inspect the request headers before the body is sent, with Expect: 100-continue.

You can create a CloudFront distribution, and configure it to redirect GET and HEAD requests from HTTP to HTTPS... but if you send a POST request to such a distribution, CloudFront doesn't redirect -- it just throws an error, since (as noted) such a redirection would be more harmful than helpful.

However... if GET is your application, then it's pretty straightforward: first, deploy your API with a Regional (not Edge-Optimized) API endpoint with a system-assigned hostname, not a custom domain.

Then, create a CloudFront distribution that uses this regional API endpoint as its origin server, and configure the CloudFront distribution's behavior to redirect HTTP to HTTPS. Associate your custom domain name with the CloudFront distribution, rather than with API Gateway directly.

Michael - sqlbot
  • 139,456
  • 21
  • 252
  • 328
  • Can you explain how to associate the custom domain with cloudfront? – Kyeotic Mar 08 '19 at 17:20
  • 1
    @Tyrsius see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html – Michael - sqlbot Mar 08 '19 at 18:55
  • 1
    Hi @Michael-sqlbot, I know that this is a pretty old answer but maybe you can help me nonetheless. I set everything up as you explained. Had most of it but had to switch from pure API Gateway to CloudFront for the http->https redirects ... if I want to disable the default API endpoint and only serve through CloudFront's custom domain, can I do that? Just disabling it leads to 404s. What do I have to use as origin domain name if I disable it. Or can't this be done when using CloudFront? – Philipp Kyeck Feb 18 '21 at 17:23