How to Configure Cloudfront

How to Configure CloudFront Amazon CloudFront is a global content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers with low latency and high transfer speeds. By caching content at edge locations around the world, CloudFront reduces the distance between users and your origin server, dramatically improving load times and user experience. Whether

Nov 6, 2025 - 10:15
Nov 6, 2025 - 10:15
 1

How to Configure CloudFront

Amazon CloudFront is a global content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers with low latency and high transfer speeds. By caching content at edge locations around the world, CloudFront reduces the distance between users and your origin server, dramatically improving load times and user experience. Whether youre managing a static website, a dynamic web application, or streaming media, configuring CloudFront correctly is essential for performance, security, and scalability.

Many organizations overlook the power of CloudFront, treating it as a simple caching layer. In reality, its a sophisticated platform that integrates with AWS services like S3, Lambda@Edge, WAF, and Origin Access Identity (OAI) to deliver enterprise-grade performance. This guide walks you through every step of configuring CloudFrontfrom initial setup to advanced optimizationensuring you maximize its potential without unnecessary complexity.

Step-by-Step Guide

Prerequisites

Before configuring CloudFront, ensure you have the following:

  • An active AWS account with appropriate permissions (preferably with IAM roles that grant access to CloudFront, S3, and other related services).
  • A domain name registered through Route 53 or another registrar (optional but recommended for custom SSL).
  • A content origin: this could be an Amazon S3 bucket, an HTTP server (like EC2 or an on-premises server), an Elastic Load Balancer, or an AWS Elemental MediaPackage.
  • Basic understanding of DNS and SSL/TLS concepts.

If youre using an S3 bucket as your origin, make sure its configured for static website hosting or is publicly accessible (if no OAI is used). For dynamic origins, ensure your server responds correctly to HTTP requests and handles CORS if needed.

Step 1: Log in to the AWS Management Console

Open your browser and navigate to https://aws.amazon.com/console/. Sign in with your AWS credentials. Once logged in, use the search bar at the top of the console to find CloudFront. Click on the CloudFront service to open the dashboard.

Step 2: Create a Distribution

On the CloudFront dashboard, click the Create Distribution button. Youll be presented with two options: Web and RTMP. For nearly all modern use cases, select Web. RTMP is legacy and only used for legacy Flash video streaming, which is obsolete.

Step 3: Configure Origin Settings

Under the Origin Settings section, youll define where CloudFront retrieves your content.

Origin Domain Name: Enter the domain name of your origin. If youre using an S3 bucket, select it from the dropdown. For custom origins (e.g., an EC2 instance or external server), enter the full domain (e.g., example.com or the public DNS of your EC2 instance).

Origin ID: This is auto-generated but can be customized for clarity. Use a descriptive name like MyS3BucketOrigin or API-Server-Prod.

Origin Path: Leave this blank unless your content resides in a subdirectory of your origin (e.g., /public). If so, enter the path to avoid serving unnecessary files.

Origin Access Identity (OAI): If your origin is an S3 bucket, always enable OAI. This restricts direct access to your S3 bucket, ensuring all requests must come through CloudFront. Click Create a new OAI, then select Yes, Update Bucket Policy to automatically apply the correct permissions.

If your origin is not S3 (e.g., a custom server), you may leave OAI disabled. However, consider securing your origin with IP whitelisting or signed URLs/cookies to prevent unauthorized access.

Step 4: Configure Default Cache Behavior

The cache behavior defines how CloudFront handles requests for your content. This is one of the most critical settings for performance and security.

Viewer Protocol Policy: Choose Redirect HTTP to HTTPS. This forces all traffic to use encrypted connections, improving security and SEO rankings.

Allowed HTTP Methods: Select GET, HEAD, OPTIONS for static content. If youre serving dynamic content (e.g., a REST API), also select PUT, POST, PATCH, DELETE as needed.

Cache Based on Selected Request Headers: For static assets (images, CSS, JS), choose None. For dynamic content, select Whitelist and include headers like Authorization, Cookie, or Origin if your backend requires them.

Object Caching: Select Use Origin Cache Headers if your origin sends proper Cache-Control and Expires headers. Otherwise, choose Customize and set a default TTL (e.g., 24 hours for static assets).

Min TTL, Max TTL, Default TTL: Set Min TTL to 0, Max TTL to 31536000 (1 year), and Default TTL to 86400 (24 hours). This gives you flexibility while ensuring stale content doesnt persist too long.

Forward Cookies: For static sites, select None. For applications requiring session cookies, choose Whitelist and specify the cookie names.

Query String Forwarding and Caching: Select None if query strings dont affect content (e.g., tracking parameters). If query strings change content (e.g., ?version=2), choose Forward all, cache based on all to avoid caching conflicts.

Step 5: Configure Distribution Settings

Scroll down to the Distribution Settings section.

Price Class: Choose based on your audience. Use All Edge Locations provides the fastest global delivery but costs more. For cost-sensitive deployments targeting North America and Europe, select Use Only North America and Europe.

Alternate Domain Names (CNAMEs): If youre using a custom domain (e.g., cdn.example.com), enter it here. Youll need to validate DNS records later.

SSL Certificate: Select Custom SSL Certificate if youve uploaded a certificate to AWS Certificate Manager (ACM). Otherwise, use the default CloudFront certificate (which works only for *.cloudfront.net). For custom domains, ACM is required and must be issued in the US East (N. Virginia) region.

Default Root Object: If your origin is an S3 static website, set this to index.html so users visiting https://cdn.example.com automatically load the homepage.

Logging: Enable logging if you need detailed analytics on requests. Specify an S3 bucket to store logs. Include cookies and referers if needed for debugging.

Origin Shield: Enable this if you have a high-volume origin. Origin Shield reduces load on your origin by adding a regional cache layer between CloudFront and your origin.

Step 6: Review and Create

Review all settings carefully. Once confirmed, click Create Distribution. CloudFront will begin provisioning your distribution. This typically takes 515 minutes. Youll see a status of InProgress. Once it changes to Deployed, your distribution is live.

Step 7: Update DNS Records

If youre using a custom domain, you must point your domain to the CloudFront distribution domain name. Log in to your DNS provider (e.g., Route 53, Cloudflare, GoDaddy) and create a CNAME record:

  • Name: cdn.example.com
  • Type: CNAME
  • Value: your-distribution-id.cloudfront.net
  • TTL: 300 seconds (5 minutes)

After saving, DNS propagation may take up to 48 hours, though it often completes in minutes. Use tools like dnschecker.org to verify propagation.

Step 8: Test Your Configuration

Once DNS is live, test your distribution:

  • Visit https://cdn.example.com in a browser. Verify your content loads.
  • Use Chrome DevTools > Network tab to check the Server header. It should show CloudFront.
  • Check cache headers: Age and X-Cache should appear in the response headers. X-Cache: Hit from cloudfront confirms caching is working.
  • Test with different geographic locations using tools like WebPageTest or GTmetrix.

Step 9: Configure Cache Invalidation (Optional)

When you update content on your origin, CloudFront may still serve cached versions. To force an update, create an invalidation:

  1. In the CloudFront console, select your distribution.
  2. Go to the Invalidations tab.
  3. Click Create Invalidation.
  4. In the Object Paths field, enter the path(s) to invalidate. Use / to invalidate everything, or /images/* to invalidate all images.
  5. Click Invalidate.

Invalidations are free for the first 1,000 paths per month. After that, AWS charges per path. Use cache control headers to minimize the need for manual invalidations.

Best Practices

Use Proper Cache-Control Headers

CloudFront respects the Cache-Control and Expires headers sent by your origin. Set these correctly to avoid over-reliance on invalidations.

  • Static assets (CSS, JS, images): Cache-Control: public, max-age=31536000, immutable
  • HTML files: Cache-Control: public, max-age=3600 (1 hour)
  • API responses: Cache-Control: private, max-age=0 (no caching)

Use versioned filenames (e.g., style.20240510.css) to bypass caching when content changes. This eliminates the need for invalidations entirely.

Enable HTTPS Everywhere

Always use HTTPS. CloudFront supports TLS 1.2 and 1.3. Configure your viewer protocol policy to redirect HTTP to HTTPS. Disable outdated protocols like TLS 1.0 and 1.1 in your distribution settings.

Secure Your Origin

Never expose your origin directly to the internet. Use Origin Access Identity (OAI) for S3 buckets. For custom origins, restrict access to CloudFronts IP ranges using security groups or WAF. AWS publishes the current CloudFront IP ranges in JSON format at https://ip-ranges.amazonaws.com/ip-ranges.json.

Implement WAF for Security

Attach an AWS WAF web ACL to your CloudFront distribution to block common threats: SQL injection, cross-site scripting (XSS), bots, and DDoS attacks. Use managed rule sets like AWS Managed Rules Core Rule Set (CRS) for immediate protection.

Use Lambda@Edge for Dynamic Content

Lambda@Edge lets you run serverless functions at CloudFront edge locations. Use it to:

  • Modify request/response headers (e.g., add security headers like Strict-Transport-Security)
  • Redirect users based on geolocation
  • Perform A/B testing or personalized content delivery
  • Authenticate requests before forwarding to origin

Deploy Lambda@Edge functions in US East (N. Virginia) and associate them with CloudFront events: Viewer Request, Origin Request, Origin Response, or Viewer Response.

Monitor Performance and Errors

Enable CloudFront access logs and send them to Amazon S3. Use Amazon CloudWatch to monitor metrics like:

  • ViewerRequests Total number of requests
  • CacheHitRate Percentage of requests served from cache
  • 4xx and 5xx Errors Identify origin or configuration issues
  • Latency Measure performance by region

Create CloudWatch alarms for high error rates or low cache hit rates to proactively address issues.

Optimize for Cost

CloudFront pricing is based on data transfer, requests, and optional features. To reduce costs:

  • Use the appropriate Price Class (avoid global if unnecessary).
  • Enable compression (Gzip or Brotli) to reduce transfer size.
  • Use Origin Shield to reduce origin load and associated bandwidth costs.
  • Cache aggressively to reduce origin requests.
  • Use S3 Transfer Acceleration only if your origin is outside the US; otherwise, CloudFront alone is faster and cheaper.

Use Signed URLs and Cookies for Private Content

For content that shouldnt be publicly accessible (e.g., paid courses, internal documents), use signed URLs or signed cookies. This allows temporary access to private objects in S3 or custom origins without exposing them.

Generate signed URLs using AWS SDKs (e.g., Python, Node.js) with a key pair and expiration time. This ensures only authorized users can access content within a limited window.

Tools and Resources

AWS CloudFront Console

The primary interface for managing CloudFront distributions. Accessible at https://console.aws.amazon.com/cloudfront/. It provides visualization of distributions, real-time metrics, and configuration controls.

AWS Certificate Manager (ACM)

Free SSL/TLS certificate management service. Request and deploy certificates for custom domains used with CloudFront. Certificates must be issued in the US East (N. Virginia) region to be used with CloudFront.

AWS WAF

Web Application Firewall that protects against OWASP Top 10 threats. Integrates seamlessly with CloudFront. Use managed rule groups like AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet for immediate protection.

AWS CLI and SDKs

Automate CloudFront configuration using the AWS CLI or SDKs. For example, to create a distribution via CLI:

aws cloudfront create-distribution --distribution-config file://dist-config.json

Use JSON templates to define origins, cache behaviors, and SSL settings programmatically. This is ideal for CI/CD pipelines and infrastructure-as-code workflows.

CloudFront Invalidation Tool (Third-party)

Tools like aws-cloudfront-invalidator automate invalidation workflows. Useful for deployments where content changes frequently.

CloudFront Metrics Dashboard (Third-party)

Platforms like Datadog, New Relic, and Splunk integrate with CloudWatch to provide advanced dashboards for performance, error rates, and geographic distribution analytics.

CloudFront Origin Shield Documentation

Official AWS guide: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html

CloudFront Best Practices Whitepaper

Download the official AWS CloudFront Best Practices guide: https://d1.awsstatic.com/whitepapers/Amazon-CloudFront-Best-Practices.pdf

CloudFront IP Ranges

For securing origins: https://ip-ranges.amazonaws.com/ip-ranges.json

Real Examples

Example 1: Static Website on S3 with CloudFront

A company hosts a marketing website on an S3 bucket. The site contains HTML, CSS, JS, and image assets.

  • Origin: S3 bucket named marketing-site-prod
  • OAI: Enabled, bucket policy updated to restrict access
  • Cache Behavior: Default TTL = 24 hours, Cache-Control headers set to 1 year for static assets
  • Custom Domain: www.company.com with ACM certificate
  • WAF: Attached with AWS Managed Rules CRS
  • Result: Page load time reduced from 3.2s to 0.8s globally. Cache hit rate improved to 98%.

Example 2: API Gateway with CloudFront and Lambda@Edge

A fintech startup uses API Gateway for its backend. To reduce latency and add security headers, they configure CloudFront as a proxy.

  • Origin: API Gateway endpoint
  • Viewer Request Lambda@Edge: Adds Strict-Transport-Security and removes Server header
  • Cache Behavior: Forward all headers and cookies; cache based on origin response
  • Origin Shield: Enabled to reduce API Gateway invocation costs
  • WAF: Blocks known bot traffic and rate-limits requests
  • Result: API response time improved by 40%. Origin requests reduced by 60% due to caching.

Example 3: Video Streaming with Signed URLs

An online education platform delivers premium video content. Videos are stored in S3 and protected with signed URLs.

  • Origin: S3 bucket with private access
  • Access: Signed URLs generated by backend (Node.js) with 1-hour expiration
  • Cache Behavior: Disable query string forwarding (signed URLs include query params)
  • SSL: Custom domain with ACM certificate
  • Result: Unauthorized access prevented. Videos load instantly from edge locations. No need for invalidations.

Example 4: Global E-commerce Site with Multi-Origin

An international e-commerce site serves static assets from S3 and dynamic product data from an EC2 cluster.

  • Two origins: static-assets.s3.amazonaws.com and api.ecommerce.example.com
  • Two cache behaviors: One for /assets/* (long TTL), one for /api/* (no caching)
  • Price Class: Use All Edge Locations
  • Logging: Enabled, logs sent to S3 for analytics
  • Result: 90% reduction in origin load. International customers experience sub-500ms load times.

FAQs

What is the difference between CloudFront and S3 static website hosting?

S3 static website hosting serves content directly from S3, which is limited to a single region. CloudFront caches that content globally at edge locations, reducing latency and improving performance for users worldwide. CloudFront also provides enhanced security, DDoS protection, and custom domain support with SSL.

Can I use CloudFront with a non-AWS origin?

Yes. CloudFront supports any HTTP(S) origin, including on-premises servers, third-party CDNs, or non-AWS cloud providers. Just ensure the origin is reachable over the public internet or via a VPC endpoint if using private connectivity.

How long does CloudFront take to deploy?

Typically 515 minutes. During deployment, CloudFront propagates your configuration to all edge locations. You cannot modify a distribution while its deploying. Wait until status changes from InProgress to Deployed.

Do I need to invalidate cache every time I update content?

No. If you use versioned filenames (e.g., app.v2.js), CloudFront will automatically serve the new file. Invalidations should be used sparingly, as they incur costs after the first 1,000 per month.

Can CloudFront serve dynamic content?

Yes. While CloudFront is optimized for static content, it can cache dynamic responses if your origin sends appropriate cache headers. For highly dynamic content (e.g., personalized dashboards), disable caching and use Lambda@Edge to modify responses at the edge.

How does CloudFront handle DDoS attacks?

CloudFront integrates with AWS Shield Standard (free) to mitigate common network and transport layer attacks. For application-layer attacks (e.g., HTTP floods), combine it with AWS WAF and AWS Shield Advanced for enhanced protection.

Is CloudFront cheaper than S3 Transfer Acceleration?

For most use cases, yes. CloudFront provides global caching, compression, and reduced origin load. S3 Transfer Acceleration only speeds up uploads to S3 and doesnt cache content. CloudFront is more cost-effective for serving content to end users.

Can I use CloudFront with a mobile app?

Absolutely. CloudFront is ideal for delivering app assets (images, JSON, SDKs) with low latency. Use signed URLs to secure private content. Combine with AWS AppSync or API Gateway for real-time data.

What happens if my origin goes down?

CloudFront will serve stale content from cache if its still valid (based on TTL). If all cached content expires and the origin is unreachable, CloudFront returns a 502 or 504 error. Use Origin Shield and implement fallback logic in your application to improve resilience.

How do I monitor CloudFront performance?

Use CloudWatch metrics (CacheHitRate, ViewerRequests, Latency), enable access logs, and integrate with third-party tools like Datadog or New Relic. Test performance globally using WebPageTest or GTmetrix.

Conclusion

Configuring Amazon CloudFront correctly transforms how your content is delivered to users around the world. From reducing latency and improving SEO rankings to enhancing security and cutting costs, CloudFront is one of the most powerful tools in the AWS ecosystem. This guide has walked you through every essential stepfrom setting up origins and cache behaviors to securing your distribution with WAF and Lambda@Edge.

Remember: CloudFront is not a set it and forget it service. Optimize it continuously by monitoring cache hit rates, updating TTLs, securing origins, and leveraging advanced features like Origin Shield and signed URLs. The best-performing websites and applications dont just rely on CloudFrontthey master it.

Start small: configure a single static site with OAI and HTTPS. Then scale to multi-origin architectures, dynamic content, and global user personalization. With each iteration, youll unlock new levels of performance, reliability, and efficiency.

CloudFront isnt just a CDN. Its your global delivery engine. Configure it wisely, and your users will never know the difference between a local server and a worldwide network.