Cloudflare Guide — CDN, DNS, DDoS Protection, and Workers
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 onlyProxied (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 pathCDN Caching
Cloudflare caches static resources at edge nodes, reducing load on your origin.
Cache configuration in dashboard
| Setting | Recommendation |
|---|---|
| Cache Level | Standard (cache static files) |
| Browser Cache TTL | 4 hours |
| Edge Cache TTL | 2 hours |
| Always Online | On (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, .aspPurge 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
| Feature | What It Blocks |
|---|---|
| Layer 3/4 | SYN floods, UDP amplification, NTP reflection |
| Layer 7 | HTTP floods, slow loris, SQLi attempts |
| Rate Limiting | Brute force login attempts, API abuse |
| Bot Management | Scrapers, 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 RequestsWAF Rules
Cloudflare’s Web Application Firewall inspects HTTP requests for malicious patterns:
| WAF Rule | Protects Against |
|---|---|
| SQL Injection | Prepared statement bypass, OR 1=1 attacks |
| XSS | Script injection, event handler payloads |
| Path Traversal | ../etc/passwd attempts |
| Remote File Inclusion | Malicious URL includes |
| Log4j | CVE-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.comWorkers 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 → OnExpected 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 → 301Common 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:
- Add your domain to Cloudflare and update nameservers at your registrar
- Create DNS records (A, CNAME, MX, TXT) with appropriate proxy settings
- Enable SSL/TLS (Full strict mode) and install origin certificate
- Create a rate limiting rule for login endpoints (10 requests/minute)
- 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,
});
},
};- 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 errorsThis setup mirrors how DodaTech protects Doda Browser API servers and distributes Durga Antivirus Pro signature updates.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro