Search code examples
amazon-s3aws-lambdaaws-api-gatewayamazon-cloudfront

How to serve static files from S3 using CloudFront


I have a CloudFront distribution in front of 2 origins:

  • S3
  • API Gateway (Lambda)

I want all the static files to be served from S3, and the rest from API Gateway.

FYI I'm trying to reproduce a classic PHP setup with static files served by Nginx and the rest served by PHP through PHP-FPM.

How can I achieve that?

What I am currently doing is this:

enter image description here

It works, but it clearly sucks because I have to add all the static file extensions manually. Is there a way to match all static files? Or to check if a file exists in S3 and serve it from there?


Solution

  • Option 1. Let the default pattern be the bucket, and create a cache behavior with the path pattern for the API, like /api/*. Possibly not practical here.

    Option 2. Match the dot before the extension for sending requests for files to S3, as /*.?? /*.??? etc. The ? placeholder matches exactly one character and without a * at the end, there must be a dot within that many characters of the end of the path.

    Option 3. Match a prefix like /assets/* and send all of these requests to the bucket. Store all your objects with assets/ at the beginning of the object key.