hosting a Cloudfront site with S3 and API Gateway
09 May 2017
Here my scenario I try to cover this time.
- host a webpage through S3 with Cloudfront as CDN
- host an API through ApiGateway with Cloudfront in front
As picture this would look like this:
The use case would be to host the API and static resources within one domain. The obvious perk of this architecture would be no more CORS dependency.
I use a CloudFormation template as project definition for this task.
So here is my YAML explained step-by-step (whole YAML is attached at the bottom).
I copied the header from an existing template since I have nothing to add here:
First I create a S3 bucket to host my page sources.
To host actual content in that bucket, I needed to create a bucket policy which allows public read access on its objects;
Now I can define the API. In this case I use a sample HelloWorldAPI, just to demonstrate the API gateway setup.
This way, the URL structure would look like this:
Now there comes the juicy part. The Cloudfront configuration is somewhat tricky since API-Gateway requires some adjustments to work.
To instantiate this template, just download the file and run the following command:
After waiting like forever, you can test your deployment with 2 separate curl commands.
Here is the overall CloudFormation template: