Search code examples
amazon-web-servicesamazon-cloudfront

Adding CloudFront for S3 but EC2 not working


I am trying to setup CloudFront with an Amazon S3 static website and Amazon EC2 nodejs server.

I have followed the following steps:

  1. Setup S3 bucket example.com
  2. Create certificate in ACM issued at example.com and api.example.com
  3. Create CloudFront distribution
  4. Set created CloudFront alternate domain names to: example.com and api.example.com
  5. Added SSL certificate from ACM
  6. Created origin with example.com.s3-website-AWS_REGION.amazonaws.com
  7. In Route 53, added entry for example.com and api.example.com with alias name pointing to CloudFront distribution.

After this my https://example.com is loading the webpage correctly. Now I try to set CloudFront for my nodejs server as well.

  1. Added new origin in CloudFront distribution with ec2-IP.AWS_REGION.compute.amazonaws.com.

  2. Added the behaviors for pattern api.example.com/* with all TTL set to zero.

Now when I try to access the nodejs server using https://api.example.com, I am not able to do so and get error. I am not sure what I am doing wrong.


Solution

  • You are confused that CloudFront serves based on virtual hosting, CloudFront doesn't do that, it instead looks at the URI path e.g: /api/* etc and forwards the requests to origin based on path behaviour match.

    In both https://api.example.com and https://example.com, it matching default path behaviour and sending requests to S3.

    Possible solution:

    1. Create a new CloudFront and add api.example.com here in CNAME and use the existing cert and origin as EC2 instance, cloudfront doesn't charge you for creating distribution.

    2. If above no, you need to use Lambda@edge(Viewer Request/Origin Request(whitelisting HOST header)) to read the HOST header and choose the origin ec2 or S3 based on if it's api.example.com or example.com.

    https://aws.amazon.com/blogs/networking-and-content-delivery/dynamically-route-viewer-requests-to-any-origin-using-lambdaedge/

    Based on your requirement, option 1 should be easy for you.