Back to HomeCDN

CDN Settings Optimization Tutorial: 8 Tips to Boost Website Speed by 50%

12 min min read
#CDN#CDN Settings#CDN Optimization#Website Speed#Cache Settings#Performance Optimization#Web Performance#Cloudflare#AWS CloudFront#Website Acceleration

CDN Settings Optimization Tutorial: 8 Tips to Boost Website Speed by 50%

CDN Settings Optimization Tutorial: 8 Tips to Boost Website Speed by 50%

Setting up a CDN is just the first step—proper optimization settings are what unlock CDN's maximum benefits. Based on our experience, many websites only see 10-20% speed improvement after adding CDN, but after optimization can reach 50% or even higher. This article shares 8 practical CDN optimization tips with hands-on guidance for creating optimal settings.

Want quick optimization? If you'd prefer professional team assistance, you can schedule an architecture consultation and we'll help you create optimal CDN settings.


Preparation Before CDN Configuration

Evaluate Current Website Status

Before optimizing CDN, understand your website's current state:

1. Measure Baseline Performance

Use these tools to test pre-optimization speed:

Record Key Metrics:

MetricDescriptionTarget Value
TTFBTime to First Byte< 200ms
LCPLargest Contentful Paint< 2.5s
FCPFirst Contentful Paint< 1.8s
CLSCumulative Layout Shift< 0.1

2. Analyze Traffic Sources

Understand your users' geographic distribution to prioritize CDN nodes:

  • Google Analytics geographic reports
  • Server log analysis
  • CDN analytics reports

3. Identify Cacheable Content

Categorize website content:

TypeExamplesRecommended Cache Time
Static assetsImages, CSS, JS, fonts1 year
Dynamic but rarely changesArticle pages, product pages1 day - 1 week
Dynamic, frequently changesUser data, real-time pricesDon't cache or short time
Sensitive dataMember areas, checkout pagesDon't cache

Want to learn more about CDN basics? See our complete guide.

Choose the Right CDN

Different CDNs have different optimization capabilities:

CDNOptimization Features
CloudflareAuto compression, Rocket Loader, Polish (image optimization)
AWS CloudFrontLambda@Edge, CloudFront Functions
AkamaiImage management, smart compression

Want to learn more about CDN vendor differences? See our comparison article. If you're evaluating CDN pricing and plans, we also have a complete pricing guide.

Backup and Test Environment

Safety measures before optimization:

  1. Backup existing settings: Screenshot or export CDN settings
  2. Prepare test environment: Use staging environment for testing
  3. Prepare rollback plan: Confirm how to quickly revert

CDN Basic Configuration

DNS Configuration

DNS is key to CDN activation:

1. Choose the Right DNS Mode

ModeDescriptionUse Case
Proxied (orange cloud)Traffic goes through CDNMain website content
DNS Only (gray cloud)Only DNS resolutionEmail, FTP

2. Set Correct TTL

  • CDN Proxied records: TTL typically controlled by CDN
  • DNS Only records: Recommend 300-3600 seconds

Origin Configuration

Correct Origin settings are the foundation for performance:

1. Use the Nearest Origin

  • Choose servers close to main users
  • Consider using Origin Shield to reduce origin fetches

2. Ensure Origin Performance

  • CDN cannot accelerate Origin processing time
  • Optimize database queries
  • Use application-layer caching

3. Secure Connection Settings

  • Use HTTPS connection to Origin
  • Set Full (Strict) SSL mode
  • Install valid SSL certificate

SSL Certificate Configuration

Best Practices:

User ──HTTPS──> CDN Edge ──HTTPS──> Origin Server
        (free cert)           (Origin cert)

Setup Steps:

  1. Install SSL certificate on Origin
  2. Set CDN to Full (Strict) mode
  3. Enable HSTS for enhanced security
  4. Force HTTPS redirect

Cache Strategy Configuration

Caching is the core of CDN performance—correct cache strategies can dramatically improve speed.

What Should Be Cached?

Should Cache:

  • Images (JPG, PNG, WebP, GIF, SVG)
  • Stylesheets (CSS)
  • JavaScript files
  • Font files (WOFF, WOFF2)
  • PDF, video, and other media files

Should Not Cache:

  • Pages containing personal data
  • API responses (unless public and rarely changing)
  • Content requiring real-time accuracy
  • Authentication-related pages

TTL Configuration Principles

TTL (Time To Live) determines cache validity:

Resource TypeRecommended TTLReason
Static assets with version numbers1 yearUpdate by changing URL
Static assets without version numbers1 weekBalance freshness and performance
HTML pages1 hour - 1 dayContent may update
API responses0 or as neededUsually needs real-time accuracy

Set Cache Headers:

Configure Cache-Control headers on Origin Server:

# Nginx example
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

location ~* \.html$ {
    expires 1h;
    add_header Cache-Control "public, must-revalidate";
}

Cache Headers (Cache-Control)

Common Cache-Control directives:

DirectiveDescription
publicCan be stored by any cache
privateOnly cacheable by browser
no-cacheMust validate with Origin
no-storeDon't cache at all
max-age=NCache for N seconds
s-maxage=NCDN cache for N seconds
immutableContent never changes
stale-while-revalidate=NCan use old cache while updating

Example Combinations:

# Static assets (with version numbers)
Cache-Control: public, max-age=31536000, immutable

# HTML pages
Cache-Control: public, max-age=3600, stale-while-revalidate=86400

# Dynamic API
Cache-Control: private, no-cache

# Sensitive data
Cache-Control: private, no-store

Dynamic Content Handling

For dynamic content, use these strategies:

1. Edge Side Includes (ESI)

  • Cache page body, fetch dynamic parts in real-time
  • Suitable for pages with public and personal sections

2. Short-time Caching

  • Even caching for just 1 minute significantly reduces Origin load
  • Suitable for traffic spike scenarios

3. Custom Cache Keys

  • Generate different caches based on specific parameters (like region, language)
  • Avoid caching wrong content

Compression and Format Optimization

Gzip vs Brotli

Comparison of two mainstream compression algorithms:

ItemGzipBrotli
Compression RateGoodBetter (~15-25%)
Compression SpeedFastSlower
Browser SupportAllModern browsers
Decompression SpeedFastEqually fast

Recommendation: Enable both Brotli and Gzip—CDN automatically selects based on browser.

CDN Settings:

Image Optimization (WebP, AVIF)

Images typically account for 50%+ of website bandwidth—optimization has significant benefits:

FormatCompression Rate (vs JPEG)Browser Support
JPEGBaselineAll
WebP25-35% smallerModern browsers
AVIF50%+ smallerNewer browsers

Auto Format Conversion:

CDNFeatureNotes
CloudflarePolish (Pro required)Auto-converts to WebP
AWS CloudFrontRequires Lambda@EdgeCustomizable logic
Bunny CDNBunny OptimizerAuto optimization

Using <picture> Tag:

<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="description">
</picture>

Minify CSS/JS

Remove whitespace, comments, etc. to reduce file size:

ResourceTypical Compression Rate
CSS10-30%
JavaScript15-40%
HTML5-15%

CDN Settings:

  • Cloudflare: Speed → Optimization → Auto Minify
  • Recommended to minify during build, CDN as backup

Advanced Optimization Techniques

Preload

Tell the browser to load critical resources ahead of time:

<!-- Preload critical CSS -->
<link rel="preload" href="/styles/critical.css" as="style">

<!-- Preload fonts -->
<link rel="preload" href="/fonts/main.woff2" as="font" crossorigin>

<!-- Preload hero image -->
<link rel="preload" href="/hero-image.webp" as="image">

Cloudflare Early Hints (HTTP 103):

  • Automatically sends preload hints
  • Starts loading resources before main response
  • Can improve load speed by 30%

Connection Optimization (HTTP/2, HTTP/3)

Modern protocols significantly improve performance:

ProtocolAdvantages
HTTP/2Multiplexing, header compression, server push
HTTP/3QUIC protocol, lower latency, better mobile network performance

CDN Settings:

  • Cloudflare: HTTP/2, HTTP/3 enabled by default
  • CloudFront: HTTP/3 requires manual enabling

Verify if Active:

curl -I --http2 https://example.com
curl -I --http3 https://example.com

Smart Routing

Advanced CDNs can choose the fastest path:

CDNFeature
Cloudflare ArgoSmart routing, ~30% average speedup
AWS CloudFrontOrigin Shield
AkamaiSureRoute

Cost Considerations:

  • Argo: $0.10/GB
  • Suitable for latency-sensitive applications

For budget-limited projects, consider free CDN plans—many free plans already include basic performance optimization features.

Need professional optimization assistance? Schedule an architecture consultation and we'll help you create optimal CDN settings.


Performance Monitoring and Testing

Using GTmetrix / PageSpeed

GTmetrix Key Metrics:

  • Performance Score: Overall performance score
  • Structure Score: Technical optimization level
  • Web Vitals: Google Core Web Vitals

PageSpeed Insights Focus:

  • Mobile and desktop scored separately
  • Provides specific optimization suggestions
  • Shows real user experience data (CrUX)

Testing Recommendations:

  • Test from different locations
  • Run multiple tests for averages
  • Record historical trends

Real User Monitoring (RUM)

Lab tests and real user experience may differ:

RUM Tools:

  • Google Analytics (Core Web Vitals reports)
  • Cloudflare Web Analytics
  • New Relic Browser
  • Datadog RUM

Metrics to Monitor:

  • Load times by region
  • Performance under different network conditions
  • Real Core Web Vitals

Cache Hit Rate Analysis

Cache hit rate is a key CDN performance indicator:

Hit RateRating
> 90%Excellent
80-90%Good
60-80%Needs optimization
< 60%Serious problem

How to Improve Hit Rate:

  1. Increase TTL
  2. Reduce Query String variation
  3. Use consistent URLs
  4. Check for no-cache headers

Cloudflare Viewing Method: Analytics → Cache → Cache Hit Ratio


Common Configuration Mistakes

Cache Configuration Errors

1. Cached Content That Shouldn't Be Cached

Problem: Users see other people's data

Solution:

  • Check if Cookies are handled correctly
  • Ensure logged-in pages use Cache-Control: private
  • Use CDN's cache bypass rules

2. Didn't Cache Content That Should Be Cached

Problem: Every request goes to origin, low CDN benefit

Solution:

  • Check Origin's Cache-Control headers
  • Remove unnecessary no-cache
  • Set forced caching rules in CDN

Origin Overload

Symptoms:

  • Low cache hit rate
  • Long Origin response times
  • Increased CDN errors

Solutions:

  1. Check if caching rules are correct
  2. Increase TTL
  3. Use Origin Shield
  4. Optimize Origin performance

SSL Mixed Content

Problem: HTTPS pages loading HTTP resources

Solution:

  • Enable Automatic HTTPS Rewrites
  • Check and fix hardcoded HTTP URLs in code
  • Use relative paths or protocol-relative URLs

Cache Preventing Content Updates

Solutions:

  1. Cache Busting

    • Add version to filename: style.v1.2.3.css
    • Add hash to URL: style.css?v=abc123
  2. Cache Invalidation

    • Cloudflare: Purge Cache
    • CloudFront: Create Invalidation
  3. Reduce TTL

    • Use shorter TTL for frequently updated content

Platform Configuration Examples

WordPress + CDN

Recommended Setup:

  1. Install Cache Plugin

    • WP Rocket
    • W3 Total Cache
    • LiteSpeed Cache
  2. Cloudflare Settings

    • Enable Automatic Platform Optimization (APO)
    • Set Page Rules to exclude wp-admin
  3. Page Rules Example

    *example.com/wp-admin/*
    → Cache Level: Bypass
    → Security Level: High
    
    *example.com/wp-login.php*
    → Cache Level: Bypass
    

Next.js + CDN

Recommended Setup:

  1. Set Cache-Control Headers

    // next.config.js
    module.exports = {
      async headers() {
        return [
          {
            source: '/_next/static/:path*',
            headers: [
              {
                key: 'Cache-Control',
                value: 'public, max-age=31536000, immutable',
              },
            ],
          },
        ]
      },
    }
    
  2. CDN Settings

    • /_next/static/* → Long-term cache
    • /api/* → Don't cache
    • Other pages → Based on ISR/SSR settings

E-commerce Platform + CDN

Key Settings:

  1. Product Pages

    • Cache public content
    • Prices/inventory fetched in real-time via API
  2. Cart/Checkout

    • Never cache
    • Set Cache-Control: private, no-store
  3. Search Results

    • Short-time cache (1-5 minutes)
    • Or don't cache
  4. CDN Rules Example

    /cart/* → Bypass Cache
    /checkout/* → Bypass Cache
    /account/* → Bypass Cache
    /products/* → Cache 1 day
    /static/* → Cache 1 year
    

Conclusion: Continuous Optimization Mindset

CDN optimization isn't a one-time task—it's a continuous improvement process:

Optimization Cycle:

  1. Measure current status
  2. Identify bottlenecks
  3. Implement improvements
  4. Verify results
  5. Repeat above steps

Key Metrics to Track:

  • Cache hit rate > 80%
  • TTFB < 200ms
  • LCP < 2.5s
  • Core Web Vitals all green

Regular Checks:

  • Monthly review CDN analytics reports
  • Quarterly evaluate if settings need adjustment
  • Test performance impact after major updates

Architecture right, speed follows. Schedule an architecture consultation and let us help you create optimal CDN settings. The CloudInsight team has helped 50+ enterprises optimize CDN settings, with average speed improvements of 45%+.


FAQ

Website got slower after CDN setup—what to do?

Possible causes: (1) Rocket Loader incompatible with JavaScript; (2) SSL mode misconfigured causing loops; (3) Origin response slowing down. Recommend first disabling advanced features, then enabling one by one to identify the problem.

How do I know if CDN cache is working?

Check HTTP Response Header for cf-cache-status (Cloudflare) or x-cache (CloudFront). HIT means cache hit, MISS means cache miss. You can also use browser developer tools to check.

Users seeing old version after content update—what to do?

Solutions: (1) Use Cache Busting by adding version numbers to file URLs; (2) Actively purge CDN cache; (3) Lower TTL settings. Recommend using version number strategy for static assets.

Does CDN affect Google Analytics data?

No. CDN only caches and delivers content—it doesn't affect JavaScript tracking code execution. But note that if caching pages with tracking code, ensure the tracking code executes correctly.

Can multiple CDNs be used simultaneously?

Yes, but not recommended. Common approach is using one main CDN for website content and another specifically for certain resources (like jsDelivr for loading libraries). Using two CDNs for the same content adds complexity.

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