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

Troubleshooting CloudFront Routing for API Gateway and S3 in a Short URL Service


I am currently working on a short URL service project that involves using AWS CloudFront to route requests to both S3 and API Gateway as origins. S3 is set up for static hosting, and there are two endpoints configured in API Gateway: /shorten_url and /{key}. The /shorten_url endpoint is designed to shorten long URLs and save them in the /u directory on S3, creating files like 1234abc, 12345ab, etc. The /{key} endpoint serves to redirect short URLs to their respective long URLs.

The behavior settings in CloudFront are configured such that the path pattern /api/* routes to the API Gateway, and the default path pattern (*) routes to the index.html file in S3.

axios
  .post("/shorten_url", postData)
  .then((response) => {
    console.log(response.data);
    this.url_short = response.data["url_short"];
  })

The /shorten_url endpoint works fine, successfully interacting with the API Gateway. However, the issue arises with the /{key} endpoint. Instead of recognizing API Gateway, it seems to bypass it entirely. I would like users to enter a short URL like www.example.com/1234abc and have it route through API Gateway and Lambda to access S3, but currently, it directly connects to S3(for example. I should like this way -> www.example.com/u/1234abc ). How can I resolve this issue to achieve the desired routing?


Solution

  • It looks like you need to configure 3 behaviours.

    1. a default behaviour routing to your S3 bucket.
    2. a behaviour associated with the prefix /api/shorten_url* and routing to your first API endpoint.
    3. a behaviour associated to another prefix (eg. /api/lenghten_url*) and routing to your second API endpoint.

    The last point kind of defeat CloudFront purpose, you want to cache content as close as possible to the user and serve this content without the need to reach your origin server(s).

    I would recommend studying CloudFront Functions and make lenghten_url a process you can run in the POPs.