Accessing static and dynamic contents through AWS CloudFront

Saravanakumar Arunachalam
4 min readMar 12, 2021
S3 and CloudFront

This article illustrates that how can we deploy a single page application in s3(Static content), dynamic content in API gateway and access through CloudFront. CloudFront enables content caching in AWS Edge location which is nearest to the end user. In this section will go though the implementation part.

To serve the dynamic content, created the sample API Gateway endpoint and added path pattern(behavior) route in CloudFront with caching disabled to the API Gateway. There will be benefits accessing the dynamic content through the CloudFront.

1. Low latency — Request will be routed through AWS network edge location for the dynamic content(AWS backed network route instead of public route).

2. Lower Cost — Data out cost will be low.

If we are not configuring dynamic content in Cloudfront and want to access the dynamic content with the direct url, then make sure to have the same subdomain to avoid the CORS issue. Example: ui.example.com, api.example.com

Steps

1. Create Sample Service in AWS API Gateway

2. Create S3 Bucket and configure it as Static Website Hosting

3. Upload the sample index.html

4. Create the CloudFront Distribution with S3 bucket as OAI (Origin Access Identity)

5. Add OAI for the API Gateway.

6. Add Behavior for the API Gateway with Path pattern (Caching Disabled)

7. Test the Changes

Serve static and dynamic content through the CloudFront

Create Sample Service in AWS API Gateway

In this example used the APT gateway endpoint to simulate the architecture. You can use any AWS public endpoint (ALB, EC2) as well. Let us create the example mock API in gateway and will walk through with dozens of screenshot

Creating sample Test mock API resource

Create S3 Bucket and configure it as Static website hosting

Let us create the S3 bucket and change the property to be Static website hosting enabled. then lets move on to the next step to configure the CloudFront

website hosting on S3

Create the CloudFront Distribution with S3 bucket as OAI (Origin Access Identity)

Let us create the CloudFront distribution and configure the OAI to restrict the direct access to S3. To understanding purpose created the many screenshots

CloudFront distribution for S3

Create the Origin for the API Gateway

Origin for the API Gateway

Create the behavior path pattern for the API gateway

Create Path Pattern

Testing — Access the UI and the Service with CloudFront Urls

Testing the endpoint with CloudFront distribution

--

--