Skip to content
Cloudflare Guide — CDN, DNS, DDoS Protection, and Workers

Cloudflare Guide — CDN, DNS, DDoS Protection, and Workers

DodaTech Updated Jun 7, 2026 9 min read

Cloudflare is a global network that provides content delivery (CDN), DNS management, DDoS protection, web application firewall (WAF), and a serverless computing platform called Cloudflare Workers. It sits between your visitors and your origin server, proxying traffic through its global edge network.

In this tutorial, you will learn how to manage DNS records through Cloudflare, configure CDN caching rules, enable DDoS protection and WAF, write and deploy Cloudflare Workers in JavaScript, and use Page Rules to customize traffic behavior. DodaTech uses Cloudflare to protect and accelerate Doda Browser API endpoints and Durga Antivirus Pro update servers.

What You’ll Learn

By the end of this guide, you will have a website behind Cloudflare’s CDN, with optimized caching, DDoS protection enabled, a custom Worker handling API routing, and Page Rules for traffic management.

Why Cloudflare Matters

Cloudflare powers over 20% of the internet’s traffic. It absorbs massive DDoS attacks (up to 2 Tbps), caches content at 310+ edge locations worldwide, and replaces traditional hardware load balancers and firewalls. For any production site, Cloudflare is the first line of defense and the fastest path to global reach.

Cloudflare Learning Path

    flowchart LR
  A[DNS Management] --> B[CDN Caching]
  B --> C[DDoS Protection]
  C --> D[WAF Rules]
  D --> E[Cloudflare Workers]
  E --> F[Page Rules]
  F --> G{You Are Here}
  style G fill:#f90,color:#fff
  

DNS Management

Cloudflare’s DNS is one of the fastest in the world, with response times under 10ms. Point your domain’s nameservers to Cloudflare, then manage records in the dashboard.

Common DNS record types:

# A record  points to an IPv4 address
example.com    A     203.0.113.10    Proxied (orange cloud)

# CNAME  points to another domain
www            CNAME    example.com    Proxied

# MX  mail exchange
@              MX    mail.example.com    DNS only (gray cloud)

# TXT  verification / SPF / DKIM
@              TXT    "v=spf1 include:_spf.google.com ~all"    DNS only

Proxied (orange cloud): Traffic passes through Cloudflare’s CDN and security. DNS only (gray cloud): Traffic goes directly to the origin without Cloudflare.

Verify DNS propagation

dig example.com +short
# → 203.0.113.10 (Cloudflare edge IP, not your origin)

dig example.com +trace
# Shows the full resolution path

CDN Caching

Cloudflare caches static resources at edge nodes, reducing load on your origin.

Cache configuration in dashboard

SettingRecommendation
Cache LevelStandard (cache static files)
Browser Cache TTL4 hours
Edge Cache TTL2 hours
Always OnlineOn (serve stale content if origin is down)

Cache by file extension

Configure page rules or Workers to cache specific content:

# Files cached automatically by default
.css, .js, .jpg, .png, .gif, .ico, .woff2, .svg

# Dynamic content (not cached by default)
.html, .php, .asp

Purge cache

# Purge everything
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"purge_everything":true}'

# Expected response
# {"success":true,"errors":[],"messages":[],"result":{"id":"..."}}

DDoS Protection

Cloudflare’s DDoS protection is always on for proxied traffic. It uses behavioral analysis and reputation scoring to filter malicious traffic.

Key protection features

FeatureWhat It Blocks
Layer 3/4SYN floods, UDP amplification, NTP reflection
Layer 7HTTP floods, slow loris, SQLi attempts
Rate LimitingBrute force login attempts, API abuse
Bot ManagementScrapers, credential stuffing

Enable Rate Limiting

# Create a rate limit rule via API
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/rate_limits" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Block brute force login",
    "match": {
      "request": {
        "url": "https://example.com/login/*",
        "methods": ["POST"],
        "schemes": ["HTTPS"]
      }
    },
    "threshold": 10,
    "period": 60,
    "action": "block",
    "action_response": {
      "type": "custom",
      "body": "Rate limit exceeded. Try again later."
    }
  }'

Expected behavior

Normal user: POST /login (3 times/minute) → 200 OK
Bot: POST /login (>10 times/minute) → 429 Too Many Requests

WAF Rules

Cloudflare’s Web Application Firewall inspects HTTP requests for malicious patterns:

WAF RuleProtects Against
SQL InjectionPrepared statement bypass, OR 1=1 attacks
XSSScript injection, event handler payloads
Path Traversal../etc/passwd attempts
Remote File InclusionMalicious URL includes
Log4jCVE-2021-44228 exploit attempts

Custom WAF rule

# Block requests from suspicious countries (example)
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/firewall/rules" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Block traffic from high-risk countries",
    "action": "block",
    "filter": {
      "expression": "(ip.geoip.country in {\"XX\" \"YY\"} and http.request.uri.path ne \"/health\")"
    }
  }'

Cloudflare Workers

Workers run JavaScript at Cloudflare’s edge nodes (310+ locations). They intercept HTTP requests and can modify, route, or respond directly — with near-zero cold starts.

Basic Worker

// Basic routing and response worker
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    // Route based on path
    if (url.pathname.startsWith('/api/')) {
      return handleAPI(request, url);
    }

    if (url.pathname === '/health') {
      return new Response('OK', { status: 200 });
    }

    // Block known bad user agents
    const userAgent = request.headers.get('User-Agent') || '';
    if (userAgent.includes('curl') && url.pathname !== '/health') {
      return new Response('Forbidden', { status: 403 });
    }

    // Forward to origin
    return fetch(request);
  },
};

async function handleAPI(request, url) {
  const apiUrl = `https://api.example.com${url.pathname}${url.search}`;
  const apiRequest = new Request(apiUrl, request);
  apiRequest.headers.set('X-Internal-Auth', env.INTERNAL_TOKEN);
  return fetch(apiRequest);
}

Deploy the Worker

# Install Wrangler CLI
npm install -g wrangler

# Log in
wrangler login

# Deploy
wrangler deploy
# Expected:
# ⛅️ Successfully published your script to https://workers.example.com

Workers KV (Key-Value Store)

// KV namespace example
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const key = url.pathname.slice(1); // Remove leading /

    if (request.method === 'GET') {
      const value = await env.MY_KV.get(key);
      return value
        ? new Response(value)
        : new Response('Not found', { status: 404 });
    }

    if (request.method === 'PUT') {
      await env.MY_KV.put(key, await request.text());
      return new Response('OK');
    }
  },
};

Page Rules

Page Rules let you customize Cloudflare behavior per URL pattern. You get 3 free rules (more on paid plans).

# Common Page Rule patterns

Pattern: example.com/wp-admin/*
Setting: Security Level → High
Setting: Disable Preloader

Pattern: example.com/*.jpg
Setting: Cache Level → Cache Everything
Setting: Edge Cache TTL → 1 month

Pattern: example.com/api/*
Setting: Cache Level → Standard
Setting: Security Level → I'm Under Attack

Pattern: example.com/*
Setting: Always Use HTTPS → On
Setting: Automatic HTTPS Rewrites → On

Expected behavior

Request to example.com/logo.jpg → Cached at edge for 1 month → 200 OK
Request to example.com/api/users → Always proxied, not cached → 200 OK
Request to example.com (without HTTPS) → Redirected to https://example.com → 301

Common Errors

1. Origin IP Leak

If DNS records are not proxied (gray cloud), attackers can bypass Cloudflare. Ensure all HTTP records show the orange cloud (proxied). Use dig to verify only Cloudflare IPs resolve.

2. SSL Handshake Errors After Enabling Cloudflare

Set SSL/TLS encryption mode to “Full (strict)” in the dashboard and install a valid origin certificate. Cloudflare’s origin CA provides free certificates for this purpose.

3. Cache Not Updating

Cloudflare caches aggressively. Purge the cache manually via the dashboard or API after updates. Use cache-busting filenames (e.g., style.v2.css) in production.

4. WAF Blocking Legitimate Traffic

Review the WAF analytics in the dashboard. Create a WAF exception for specific paths, IPs, or ASNs. Log the requests before blocking.

5. Worker Returning 500 Without Clarity

Add error logging in Workers:

try {
  const response = await fetch(request);
  return response;
} catch (err) {
  console.error(`Worker error: ${err.message}`);
  return new Response(`Worker error: ${err.message}`, { status: 500 });
}

Check logs via wrangler tail.

6. Rate Limiting False Positives

Rate limiting counts all requests, including legitimate API calls. Use the “Mitigation Expression” to exclude paths or methods. Increase the threshold if your API has high legitimate traffic.

7. Nameserver Change Not Propagating

DNS changes take 24-48 hours globally. Verify with whatsmydns.net. Keep the old DNS provider’s records active during migration.

Practice Questions

1. What is the difference between a proxied (orange cloud) and DNS-only (gray cloud) record?

Proxied traffic passes through Cloudflare’s CDN and security services. DNS-only traffic bypasses Cloudflare and goes directly to the origin server.

2. How do you purge the Cloudflare cache?

Through the dashboard (Caching → Purge Everything), via API (purge_cache endpoint), or using wrangler for Workers-specific caches.

3. What is the purpose of Cloudflare Workers?

Workers are serverless functions that run at Cloudflare’s edge (310+ locations). They intercept HTTP requests and can modify, route, or respond directly without reaching the origin server.

4. How does Cloudflare protect against DDoS attacks?

Cloudflare’s global network absorbs traffic and uses behavioral analysis, IP reputation, and rate limiting to filter malicious traffic before it reaches the origin.

5. Challenge: Create a redirect Worker

Write a Worker that redirects example.com/* to www.example.com/* with a 301 status, preserving the path and query string.

Mini Project: Full Cloudflare Setup

Configure Cloudflare for a production website:

  1. Add your domain to Cloudflare and update nameservers at your registrar
  2. Create DNS records (A, CNAME, MX, TXT) with appropriate proxy settings
  3. Enable SSL/TLS (Full strict mode) and install origin certificate
  4. Create a rate limiting rule for login endpoints (10 requests/minute)
  5. Deploy a Worker that adds security headers:
export default {
  async fetch(request, env, ctx) {
    const response = await fetch(request);
    const newHeaders = new Headers(response.headers);
    newHeaders.set('X-Content-Type-Options', 'nosniff');
    newHeaders.set('X-Frame-Options', 'DENY');
    newHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin');
    newHeaders.set('Permissions-Policy', 'geolocation=()');
    return new Response(response.body, {
      status: response.status,
      headers: newHeaders,
    });
  },
};
  1. Create Page Rules: Always Use HTTPS, cache static assets for 30 days

Test:

# Verify security headers
curl -I https://yourdomain.com
# Expect: X-Content-Type-Options: nosniff, etc.

# Verify rate limiting
for i in $(seq 1 15); do
  curl -X POST https://yourdomain.com/login
done
# After 10 requests, you should see 429 errors

This setup mirrors how DodaTech protects Doda Browser API servers and distributes Durga Antivirus Pro signature updates.

FAQ

Is Cloudflare free?
Cloudflare offers a generous free plan that includes CDN, DNS, DDoS protection, SSL, and 3 Page Rules. Workers have a free tier with 100,000 requests/day.
Does Cloudflare slow down my site?
No — Cloudflare typically speeds up sites. Static content is cached at edge nodes. Dynamic content routes through optimized paths with persistent connections. The average latency improvement is 40-60%.
Can I use Cloudflare with any hosting provider?
Yes — Cloudflare sits in front of any origin server. It works with AWS, DigitalOcean, shared hosting, or even a home server.
What happens if my origin goes down?
If Always Online is enabled, Cloudflare serves cached versions of your pages. This prevents downtime during brief origin outages.
How do Cloudflare Workers compare to AWS Lambda?
Workers start in under 5ms (vs 100ms+ for Lambda cold starts). They run at the edge (310+ locations) instead of a single region. Workers are best for latency-sensitive, globally-distributed logic.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro