Back to HomeCDN

AWS CloudFront Tutorial: Complete CDN Setup and Optimization in 7 Steps

14 min min read

AWS CloudFront Tutorial: Complete CDN Setup and Optimization in 7 Steps

AWS CloudFront Tutorial: Complete CDN Setup and Optimization in 7 Steps

AWS CloudFront is Amazon Web Services' CDN service, deeply integrated with the AWS ecosystem, making it the preferred choice for enterprise applications. This article will guide you through CloudFront setup from basic concepts, including S3 static website integration, EC2/ALB dynamic application integration, and best practices for performance and cost optimization.

Need help with AWS architecture design? Schedule an architecture consultation, and let our AWS certified architects assist you.


CloudFront Introduction

What is AWS CloudFront?

AWS CloudFront is Amazon's global Content Delivery Network (CDN), with over 450 Edge Locations in 47 countries and 13 Regional Edge Caches worldwide.

To learn more about CDN fundamentals and how they work, check out our complete guide.

CloudFront main features:

FeatureDescription
Deep AWS IntegrationSeamless integration with S3, EC2, ALB, Lambda@Edge
Global Coverage450+ edge locations across six continents
Security ProtectionBuilt-in AWS Shield Standard, WAF integration available
Flexible BillingPay-per-use, no minimum spend
Real-time LogsExport to S3, CloudWatch for analysis

CloudFront vs Other CDNs

ComparisonCloudFrontCloudflareAkamai
Free TierYes (1TB/month for 12 months)Yes (unlimited traffic)No
AWS IntegrationNativeRequires additional setupRequires additional setup
Configuration ComplexityMediumSimpleComplex
Best ForAWS usersGeneral websitesLarge enterprises

To learn more about comprehensive CDN provider comparisons, check out our comparison article.


CloudFront Core Concepts

Before starting configuration, you need to understand four core concepts:

Distribution

Distribution is CloudFront's basic configuration unit, containing all CDN settings such as Origin, cache behavior, SSL certificates, etc.

Types:

  • Web Distribution: For websites and APIs (most common)
  • RTMP Distribution: For streaming media (discontinued for new creations)

Origin

Origin is where your content is stored. CloudFront fetches content from the Origin and caches it.

Common Origin Types:

  • S3 Bucket (static content)
  • ALB/ELB (dynamic content)
  • EC2 Instance (direct connection)
  • Custom Origin (any HTTP/HTTPS server)
  • MediaStore / MediaPackage (streaming content)

Edge Location

Edge Locations are the actual locations where content is cached, distributed globally. User requests are routed to the nearest Edge Location.

Major Asia Pacific Nodes:

  • Taiwan: Taipei
  • Japan: Tokyo, Osaka
  • Korea: Seoul
  • Hong Kong
  • Singapore
  • Australia: Sydney, Melbourne

Cache Behavior

Cache Behavior determines how CloudFront handles requests for different paths.

Configurable Items:

  • URL Path Pattern
  • Allowed HTTP Methods
  • Cache Policy
  • Origin Request Policy
  • Compression
  • Lambda@Edge Triggers

Creating Your First Distribution

Step 1: Access CloudFront Console

  1. Log into AWS Console
  2. Search for "CloudFront" or find it in the service list
  3. Click "Create Distribution"

Step 2: Configure Origin

Origin Domain: Enter your source domain

  • S3: Select S3 bucket (will auto-populate)
  • ALB/EC2: Enter DNS name or IP

Origin Path: Optional, specify a particular path (e.g., /public)

Origin Access:

  • Public: Origin is publicly accessible
  • Origin Access Control (OAC): Restrict access to CloudFront only (recommended for S3)
  • Origin Access Identity (OAI): Legacy setting, OAC recommended

Protocol:

  • HTTPS Only (recommended)
  • Match Viewer
  • HTTP Only (not recommended)

Step 3: Configure Default Cache Behavior

Path Pattern: Default is * (matches all requests)

Compress Objects Automatically: Recommended to enable

Viewer Protocol Policy:

  • HTTP and HTTPS
  • Redirect HTTP to HTTPS (recommended)
  • HTTPS Only

Allowed HTTP Methods:

  • GET, HEAD (static content)
  • GET, HEAD, OPTIONS
  • GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE (APIs)

Cache Key and Origin Requests:

  • Cache Policy: Select or create cache policy
  • Origin Request Policy: Select headers to forward to Origin

Step 4: Configure Distribution Settings

Price Class: Determines which regional nodes to use

  • Use All Edge Locations (best performance, highest cost)
  • Use North America, Europe, Asia, Middle East, and Africa
  • Use Only North America and Europe (lowest cost)

AWS WAF: Optionally integrate with WAF

Alternate Domain Names (CNAMEs): Enter your custom domain

Custom SSL Certificate: Select ACM certificate

Default Root Object: e.g., index.html

Step 5: Create and Wait for Deployment

After clicking "Create Distribution," wait 5-15 minutes for deployment. Status will change from "In Progress" to "Deployed."

Once deployed, you'll receive a CloudFront domain name (e.g., d1234567890.cloudfront.net) for testing.


Integrating S3 Static Websites

S3 + CloudFront is the most common static website architecture, suitable for blogs, corporate websites, and SPA applications.

S3 Bucket Configuration

1. Create Bucket

  • Name should match your domain (e.g., www.example.com)
  • Select region close to primary users

2. Upload Files

  • Upload HTML, CSS, JS, images, and other static files

3. No Need to Enable Static Website Hosting

  • When using OAC, enabling public access is neither necessary nor recommended

Origin Access Control (OAC) Configuration

OAC is AWS's recommended new method, replacing the older OAI:

1. Create OAC

  • CloudFront Console → Origin Access → Create Control Setting
  • Enter name, use default values for other settings

2. Select OAC in Distribution

  • Origin Access → Origin Access Control Settings
  • Select the OAC you just created

3. Update S3 Bucket Policy CloudFront will provide a Policy; copy and paste it to S3 Bucket Policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipal",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your-bucket-name/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE"
                }
            }
        }
    ]
}

SPA Application Configuration

For React, Vue, Angular, and other SPAs, additional error page handling is needed:

Custom Error Response:

  • HTTP Error Code: 403
  • Response Page Path: /index.html
  • HTTP Response Code: 200

This way, when users directly access paths like /about, CloudFront returns index.html, letting frontend routing handle it.


Integrating EC2 / ALB

For dynamic content, CloudFront typically integrates with ALB (Application Load Balancer).

ALB as Origin

1. Configure Origin Domain

  • Enter ALB's DNS name (e.g., my-alb-123456.us-east-1.elb.amazonaws.com)

2. Protocol

  • Recommend HTTPS Only
  • Ensure ALB has SSL certificate configured

3. Origin Shield

  • Optional, reduces requests to Origin
  • Recommend selecting same or nearest region to ALB

Dynamic Content Cache Strategy

For APIs or dynamic content, special cache behavior configuration is needed:

Non-cached paths (e.g., /api/*):

  • Cache Policy: CachingDisabled
  • Origin Request Policy: AllViewerExceptHostHeader

Partially cached paths (e.g., /products/*):

  • Cache Policy: Custom with shorter TTL
  • Can differentiate cache by Query String or Cookie

Health Check Configuration

CloudFront automatically monitors Origin health, but you can adjust:

Origin Connection Attempts: Default 3 times

Origin Connection Timeout: Default 10 seconds

Origin Read Timeout: Default 30 seconds

Origin Keepalive Timeout: Default 5 seconds

Need a second opinion on architecture design? Schedule an architecture consultation, our AWS certified architects will provide professional advice.


SSL Certificate Configuration

Using Free ACM Certificates

AWS Certificate Manager (ACM) provides free SSL certificates:

Important: CloudFront can only use ACM certificates from the us-east-1 (N. Virginia) region.

Application Steps:

  1. Switch to us-east-1 region
  2. Go to ACM Console → Request Certificate
  3. Select Public Certificate
  4. Enter domain names (e.g., example.com, *.example.com)
  5. Select validation method (DNS Validation recommended)
  6. Add validation record in DNS
  7. Wait for certificate status to become Issued

Custom Domain Configuration

1. Add Alternate Domain Names (CNAMEs) in Distribution

2. Select SSL Certificate

  • Custom SSL Certificate
  • Select the ACM certificate you just applied for

3. Add CNAME Record in DNS

  • Name: www
  • Value: d1234567890.cloudfront.net (your CloudFront domain)

HTTPS Forced Redirect

Configure Viewer Protocol Policy:

  • Redirect HTTP to HTTPS (recommended)

This automatically 301 redirects all HTTP requests to HTTPS.


Cache Optimization Strategies

Cache Policy Configuration

AWS provides default Cache Policies, or you can customize:

Default Policies:

Policy NameTTLUse Case
CachingOptimizedDefault 24 hours, max 1 yearStatic resources
CachingDisabledNo cachingAPIs, dynamic content
CachingOptimizedForUncompressedObjectsSame as above, no compressionPre-compressed content

Custom Policy Settings:

  • Minimum TTL: Shortest cache time
  • Maximum TTL: Longest cache time
  • Default TTL: Default when Origin doesn't specify
  • Cache Key Settings:
    • Headers: Which headers to include in cache key
    • Cookies: Which cookies to include in cache key
    • Query Strings: Which parameters to include in cache key

TTL Configuration Guidelines

Resource TypeRecommended TTLNotes
HTML5 minutes - 1 hourContent may update frequently
CSS/JS (versioned)1 yearUpdate via Cache Busting
Images1 month - 1 yearUsually don't change often
API Responses0 or very shortDepends on business needs
User-specific content0Should not be cached

Cache Invalidation

When you need to force cache updates:

1. Console Operation

  • CloudFront → Distribution → Invalidations → Create Invalidation
  • Enter paths (e.g., /images/* or /*)

2. CLI Operation

aws cloudfront create-invalidation \
    --distribution-id E1234567890 \
    --paths "/*"

3. Cost Notice

  • First 1,000 paths per month are free
  • $0.005 per path thereafter

Recommendation: Rather than frequent invalidations, use Cache Busting (adding version numbers to filenames).


Security Configuration

AWS Shield Integration

CloudFront automatically includes AWS Shield Standard, providing:

  • Layer 3/4 DDoS protection
  • No additional cost

Shield Advanced (paid) provides:

  • Layer 7 DDoS protection
  • 24/7 DDoS Response Team
  • Cost protection (compensation for attack-related extra costs)
  • Cost: Starting at $3,000/month

WAF Integration

AWS WAF can integrate with CloudFront, providing:

  • SQL Injection protection
  • XSS protection
  • Rate Limiting
  • IP whitelist/blacklist
  • Geo-blocking

Configuration:

  1. Create Web ACL in WAF Console
  2. Select CloudFront (Global) for region
  3. Add rules (can use AWS Managed Rules)
  4. Associate Web ACL in CloudFront Distribution

To learn more about CDN and DDoS protection, check out our dedicated article.

Geographic Restrictions

CloudFront can allow or block access based on user geographic location:

Setting Location: Distribution → Security → Restrictions → Geo Restriction

Options:

  • Allow list: Only allow specific countries
  • Block list: Block specific countries

Signed URLs / Cookies

For content requiring access control (e.g., paid content), use signing:

Signed URLs: Suitable for single files Signed Cookies: Suitable for multiple files or streaming


Cost Optimization

Price Class Selection

Different Price Classes have significant cost differences:

Price ClassCoverageCost Difference
All Edge LocationsGlobalHighest
200 (excludes some South America, Australia)North America, Europe, AsiaMedium
100North America, EuropeLowest

Recommendation: If primary users are in Asia, selecting Price Class 200 balances performance and cost.

Compression Settings

Enabling automatic compression reduces transfer volume and costs:

Setting Location: Cache Behavior → Compress Objects Automatically → Yes

Supported compression formats:

  • Gzip
  • Brotli (more efficient)

Savings Effect: Typically reduces transfer volume by 60-80%

For more CDN optimization tips, see CDN Settings Optimization Tutorial.

Monitoring and Budget Alerts

CloudWatch Metrics:

  • Requests: Number of requests
  • BytesDownloaded: Transfer volume
  • 4xxErrorRate / 5xxErrorRate: Error rates

Setting Budget Alerts:

  1. AWS Budgets → Create Budget
  2. Set monthly budget amount
  3. Set alert thresholds (e.g., 80%, 100%)
  4. Set notification method (Email, SNS)

To learn more about CDN costs and money-saving tips, check out our pricing guide.


Common Problem Troubleshooting

403 Forbidden Error

Possible Causes:

  1. S3 Bucket Policy not configured correctly
  2. OAC/OAI configuration error
  3. S3 Block Public Access settings
  4. File doesn't exist

Solution Steps:

  1. Confirm Bucket Policy includes CloudFront access permissions
  2. Confirm OAC is configured correctly
  3. Confirm file path is correct

504 Gateway Timeout

Possible Causes:

  1. Origin responding too slowly
  2. Origin health check failed
  3. Origin Timeout set too short

Solution Steps:

  1. Check if Origin is operating normally
  2. Increase Origin Read Timeout (max 60 seconds)
  3. Optimize Origin performance

Cache Not Updating

Possible Causes:

  1. Cache hasn't expired yet
  2. Browser cache
  3. TTL set too long

Solution Steps:

  1. Create Invalidation to clear cache
  2. Clear browser cache or test in incognito mode
  3. Adjust TTL settings
  4. Use Cache Busting (add version parameter to URL)

Performance Tuning

Check Items:

  1. Cache Hit Ratio: Target > 80%
  2. Origin Latency: Check Origin response time
  3. Edge Location: Confirm users connect to correct node

Optimization Directions:

  1. Increase cache coverage
  2. Use Origin Shield to reduce Origin load
  3. Consider Lambda@Edge for edge computing

Advanced Features

Lambda@Edge

Execute custom code at edge locations:

Use Cases:

  • A/B Testing
  • Dynamic content generation
  • URL rewriting
  • Authentication verification
  • Header modification

Trigger Points:

  • Viewer Request: User request arrives at Edge
  • Viewer Response: Before response is sent to user
  • Origin Request: Before request is sent to Origin
  • Origin Response: After Origin response arrives at Edge

CloudFront Functions

Lighter and faster edge computing than Lambda@Edge:

Limitations:

  • Can only be used for Viewer Request/Response
  • Maximum execution time 1ms
  • Maximum memory 2MB

Suitable Scenarios:

  • URL rewriting
  • Header modification
  • Simple request validation

Origin Shield

Add an additional cache layer in front of Origin:

Benefits:

  • Reduce Origin load
  • Improve cache hit ratio
  • Lower Origin costs

Cost: Charged per request


Real-World Example: E-commerce Website Architecture

A typical e-commerce website CloudFront architecture:

Architecture:

User → CloudFront → ALB → EC2 Auto Scaling Group
                  ↘ S3 (static resources)

Cache Behavior Configuration:

PathOriginCache Policy
/api/*ALBCachingDisabled
/static/*S3CachingOptimized (1 year)
/images/*S3CachingOptimized (1 month)
Default (*)ALBCustom (5 minutes)

Security Configuration:

  • WAF enabled with AWS Managed Rules
  • Rate Limiting to prevent brute force attacks
  • Geographic restrictions allowing only service regions

Conclusion: Building High-Performance AWS Architecture

After completing this article's configuration, your CloudFront should have:

  • Distribution correctly configured and deployed
  • S3 or ALB Origin connected properly
  • SSL certificate configured
  • Cache strategy optimized
  • Basic security protection enabled

Next Steps:

  1. Monitor CloudWatch Metrics to confirm performance indicators
  2. Set up Budget Alerts to control costs
  3. Regularly review access logs to optimize cache strategy
  4. Consider whether Lambda@Edge is needed for advanced processing

Good architecture can save multiples in operational costs. Schedule an architecture consultation, let us review your cloud architecture together. The CloudInsight team has multiple AWS Certified Solutions Architects who have helped over 100 enterprises optimize their AWS architecture.


FAQ

What's the Difference Between CloudFront and S3 Transfer Acceleration?

CloudFront is a complete CDN service providing caching, security protection, and other features. S3 Transfer Acceleration only accelerates uploads to S3. If you need to accelerate website content delivery, you should use CloudFront.

How Much Free Tier Does CloudFront Have?

AWS Free Tier includes 1TB transfer and 10,000,000 HTTP/HTTPS requests per month, for 12 months. Beyond that, charges apply per usage, approximately $0.12/GB in Asia Pacific.

Can I Use CloudFront and Cloudflare Together?

Technically possible, but generally not recommended. Two CDN layers increase complexity and latency. If you're already using AWS, CloudFront is a better choice; if you're using other clouds or need a free plan, Cloudflare is more suitable.

Does CloudFront Support HTTP/3?

Yes, CloudFront supports HTTP/3 (QUIC). It can be enabled in Distribution settings and improves performance for mobile network users.

How Do I Migrate an Existing Website to CloudFront?

Recommended steps: (1) First create a CloudFront Distribution pointing to existing Origin; (2) Test using CloudFront domain; (3) Once confirmed working, point DNS to CloudFront. The entire process can achieve zero-downtime migration.

Need Professional Cloud Advice?

Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help

Book Free Consultation

Related Articles