Search code examples
amazon-web-servicesaws-api-gatewayamazon-cloudfront

How to use API Gateway as a CloudFront origin configuration


For context, I'm building a small application that uses Django and Vue.js. I want to do the following:

  1. send Django requests (/api/ and /admin/) to API Gateway where they are served in AWS Lambda functions
  2. serve requests to /media/ and /assets/ with an S3 Origin in CloudFront
  3. serve all other requests with an S3 website where the static assets for my Vue.js application are stored

I'm wondering if it is possible to do this using the same domain/subdomain for each of the three CloudFront origin configurations.

I know how to setup a custom domain name for API Gateway, for example api.mysite.com. If I have the CloudFront distribution pointing to it with a Route53 A record for mysite.com, I was thinking that I could setup a custom origin configuration that points to api.mysite.com on path patterns of /api/ and /admin/. Trying this resulted in a 502 error on CloudFront when I tried accessing mysite.com/api/health-check/, but I get a healthy health check when I access api.mysite.com/api/health-check/ (the API Gateway custom domain name).

I think I'm having an XY Problem, because I'm not sure that this is advised or even possible. Should I just use a different subdomain for API Gateway and setup CORS so my Vue application can make requests to the Django API? Or would it be possible to use one CloudFront distribution for an S3 website, S3 Origin and API Gateway?

I'm using CDK to define all of my infrastructure. I have previously used ALB on the same domain name as the S3 website and can make requests to the API on the same domain name without needing CORS, but I'm new to API Gateway and not sure how their custom domain names work yet. Also, the fact that stage is appended to the URL for the API Gateway domain is confusing for me, I'm not sure if or how this would play into my solution for this problem.


Solution

  • You can use multiple origins within the same CloudFront distribution to get around this problem.

    You would have the following setup:

    • Default origin - Route to your S3 Website
    • Origin for '/api/*' - Route to API Gateway
    • Origin for '/admin/*' - Route to API Gateway
    • Origin for '/media/*' - Route to S3 Origin
    • Origin for '/assets/*' - Route to S3 Origin

    Additional origins after the default support path based routing (although an origin can only support a single path).

    If this is all setup then you can assign your hostname to the single CloudFront distribution.

    Here is more information on setting up multiple origins.