Search code examples
amazon-web-servicesamazon-cloudfrontaws-api-gateway

How can I use AWS CloudFront and API Gateway side by side for the same domain?


I'm putting that static assets of my website on S3, and setting up CloudFront to distribute them. These essentially holds the content users would need for any GET request on my site, to existing paths that is, with a catchall for errors.

I also have some POST requests I need to handle. Form submissions, sending emails, notifications, interacting with the database.

How can I set up Lambda (or API Gateway) side by side with CloudFront for the same domain so that CloudFront handles GET requests, and API Gateway handles requests with a body or POST requests. Or can I do it by individual URL somehow?


Solution

  • Create the distribution in CloudFront and get it working with S3.

    Then add a second origin, pointing to the hostname assigned in API Gateway.

    Then create a second Cache Behavior in CloudFront, using the API Gateway origin, setting it for the appropriate Path Pattern (such as /api/*) that API Gateway expects, and configure it to forward all methods (GET, POST, PUT, etc... the default is only GET and HEAD but there's a radio button to enable all methods). You'll probably want to forward some headers, so select those... but don't forward the original Host header, because that won't work. You may also want to forward query string or cookies, and those need to be enabled on that same screen.

    That's pretty much it. CloudFront sends the requests to the appropriate backend, based on path matching.