Protect Your Domain with Cloudflare: The Complete Security & Performance Guide

Harden your domain in 7 days — DNS delegation, DNSSEC, SSL/TLS, WAF rules, DDoS mitigation, rate limiting, bot management, origin hardening, caching, Workers and Zero Trust, with practical examples and configuration snippets.

1. Why Cloudflare?

Cloudflare operates one of the world's largest edge networks (310+ cities). Placing it in front of your domain gives you:

  • DDoS absorption — Volumetric attacks are filtered before they touch your server.
  • Free SSL/TLS — Automatic certificates, no manual renewal.
  • Fast DNS — ~11 ms median resolution time worldwide.
  • WAF — Blocks SQLi, XSS, RCE and known CVE exploits.
  • Global CDN — Static assets cached at the edge, reducing origin load and latency.
  • Bot mitigation — Separates human from automated traffic.
  • Free tier — Most of the above is available on the free plan.

2. How Cloudflare Works

Visitor → Cloudflare Edge (DNS, TLS, WAF, Cache) → Your Origin Server

┌──────────┐      ┌──────────────────────────┐      ┌──────────────┐
│  Browser  │─────▶│  Cloudflare Edge Node     │─────▶│  Your Server │
│           │◀─────│  (DNS, TLS, WAF, CDN)     │◀─────│  (Origin)    │
└──────────┘      └──────────────────────────┘      └──────────────┘
                  ↕                              
            Cached response (if hit)
  1. Visitor's DNS query resolves to Cloudflare's edge IP (not your origin IP).
  2. Cloudflare terminates TLS, inspects the request (WAF, bot score, rate limit).
  3. If the response is cached, Cloudflare returns it directly (cache hit).
  4. If not cached, Cloudflare forwards the request to your origin, caches the response, and returns it.

3. Plans & What's Free

  • Free — DNS, CDN, basic DDoS, 5 Page Rules, limited WAF managed rules, rate limiting (1 rule), Cloudflare Workers (100k requests/day).
  • Pro ($20/mo) — WAF with OWASP rules, image optimization (Polish), mobile optimization, 20 Page Rules.
  • Business ($200/mo) — Custom WAF rules, advanced bot management, 50 Page Rules, SLA.
  • Enterprise — Dedicated support, advanced DDoS, custom configurations, 125+ Page Rules.

For most small-to-medium sites, the free plan provides excellent protection. Upgrade to Pro when you need OWASP WAF rules.

4. DNS Setup & Delegation

  1. Create a free Cloudflare account at dash.cloudflare.com.
  2. Click Add a site and enter your domain.
  3. Cloudflare scans your existing DNS records automatically.
  4. Review the imported records — verify A, AAAA, CNAME records are correct.
  5. Cloudflare assigns two name servers (e.g., anna.ns.cloudflare.com, bob.ns.cloudflare.com).
  6. At your domain registrar, replace the existing name servers with Cloudflare's.
  7. Wait for propagation (usually 10 min – 24 hours). Cloudflare confirms when active.

Proxy mode (orange cloud vs. grey cloud)

  • Proxied (orange cloud) — Traffic flows through Cloudflare; WAF, CDN, DDoS active. Use for web traffic.
  • DNS only (grey cloud) — Cloudflare only provides DNS resolution; no security/CDN features. Use for MX records, non-HTTP services.

5. DNSSEC

DNSSEC (DNS Security Extensions) adds cryptographic signatures to DNS records, preventing forgery and cache poisoning.

  1. In Cloudflare dashboard: DNS → DNSSEC → Enable.
  2. Cloudflare generates a DS record.
  3. Add the DS record at your domain registrar (Namecheap, GoDaddy, Google Domains, etc.).
  4. Verify with: dig +short DS yourdomain.com

6. SSL/TLS Configuration

Encryption modes

  • Off — No encryption. Never use this.
  • Flexible — Encrypted between visitor ↔ Cloudflare, but not between Cloudflare ↔ origin. Better than nothing, but origin traffic is plain HTTP.
  • Full — Encrypted both ways, but Cloudflare doesn't validate the origin certificate (accepts self-signed).
  • Full (Strict) — Encrypted both ways; origin must have a valid, trusted certificate. Recommended.

Origin certificate

If your origin doesn't have a certificate, Cloudflare can generate a free Origin Certificate (valid 15 years, trusted only by Cloudflare). Install it on your server and set mode to Full (Strict).

# Generate an Origin Certificate:
# Cloudflare Dashboard → SSL/TLS → Origin Server → Create Certificate
# Download the .pem and .key files
# Install on your web server (Nginx example):

server {
  listen 443 ssl;
  server_name example.com;
  ssl_certificate     /etc/ssl/cloudflare-origin.pem;
  ssl_certificate_key /etc/ssl/cloudflare-origin.key;
}

7. HSTS & HTTPS Enforcement

  • Always Use HTTPS — Enable in SSL/TLS → Edge Certificates. Redirects all HTTP requests to HTTPS.
  • Automatic HTTPS Rewrites — Fixes mixed-content issues by rewriting HTTP URLs to HTTPS inline.
  • HSTS — Add the header to tell browsers to always use HTTPS:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Start with a short max-age (e.g., 300) when testing. Once confident, increase to 31536000 (1 year) and submit to the HSTS preload list.

8. Web Application Firewall (WAF)

The WAF inspects every HTTP request and blocks known attack patterns.

Managed rules

  • Cloudflare Managed Ruleset — Covers common vulnerabilities (SQLi, XSS, RCE, path traversal).
  • OWASP Core Ruleset — Available on Pro+. Implements OWASP ModSecurity rules.
  • Exposed Credentials Check — Warns if credentials appear in known breach databases.

Tuning the WAF

After enabling, monitor the Security → Events log. If legitimate requests are blocked (false positives):

  1. Identify the rule ID causing the block.
  2. Create an exception (skip rule) for that specific URL pattern or user agent.
  3. Re-test and verify the exception works without weakening protection.

9. DDoS Protection

Cloudflare provides unmetered DDoS protection on all plans, including free:

  • Layer 3/4 — Network-level floods (SYN, UDP, amplification) are absorbed at the edge.
  • Layer 7 — Application-level floods (HTTP floods) are mitigated by the WAF and challenge mechanisms.
  • "Under Attack" mode — If you're actively being attacked, enable this in the dashboard. Cloudflare shows a JavaScript challenge to all visitors for ~5 seconds before allowing access.

10. Rate Limiting

Protect endpoints from brute-force attacks and abuse:

// Example: Limit login endpoint
URL pattern: /api/login
Threshold: 5 requests per 10 seconds per IP
Action: Block for 60 seconds
Response: 429 Too Many Requests

// Example: Limit contact form
URL pattern: /contact
Threshold: 3 requests per minute per IP
Action: Challenge (CAPTCHA)

On the free plan you get 1 rate limiting rule. Pro and above get more rules and advanced matching (headers, cookies, etc.).

11. Bot Management

  • Bot Fight Mode (free) — Challenges automated traffic using JavaScript challenges and fingerprinting.
  • Super Bot Fight Mode (Pro+) — More granular: block definitely automated, challenge likely automated, allow verified bots (Googlebot, etc.).
  • Bot Management (Enterprise) — ML-based scoring per request; integrate with firewall rules.

Enable Bot Fight Mode under Security → Bots. This reduces scraping, credential stuffing and spam with zero configuration.

12. Custom Firewall Rules

// Block a specific IP range
(ip.src in {198.51.100.0/24})
Action: Block

// Challenge requests from high-threat-score countries
(ip.geoip.country in {"XX" "YY"}) and (cf.threat_score gt 20)
Action: Managed Challenge

// Block requests targeting wp-admin from non-allowed IPs
(http.request.uri.path contains "/wp-admin") and not (ip.src in {YOUR_IP})
Action: Block

// Allow verified bots (Googlebot, Bingbot)
(cf.client.bot)
Action: Allow

Free plan: 5 firewall rules. Pro: 20. Business: 100.

13. Origin Server Hardening

Without origin hardening, attackers can bypass Cloudflare by connecting directly to your server IP.

  • Firewall — Allow only Cloudflare IPs:
# iptables example: allow only Cloudflare ranges on port 443
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
  iptables -A INPUT -p tcp --dport 443 -s "$ip" -j ACCEPT
done
iptables -A INPUT -p tcp --dport 443 -j DROP
  • Authenticated Origin Pulls — Cloudflare sends a client certificate to your origin; reject requests without it.
  • Secret header — Configure a secret header in Cloudflare Workers that your origin validates.
  • Hide your origin IP — Never expose it in DNS records, email headers or error pages.

14. Caching & Performance

  • Cache Everything — For static sites, use a Page Rule with "Cache Level: Cache Everything" to cache HTML at the edge.
  • Browser Cache TTL — Set to 4 hours+ for static assets. Cloudflare respects Cache-Control headers from your origin.
  • Edge Cache TTL — How long Cloudflare caches at the edge. Set per resource type.
  • Purge cache — Dashboard → Caching → Purge Everything (or purge by URL).
  • Polish (Pro+) — Automatic image compression (lossless or lossy).
  • Mirage (Pro+) — Lazy-loads images and serves appropriately sized images for mobile.
  • Auto Minify — Minifies HTML, CSS and JavaScript at the edge.
  • Early Hints — Sends 103 responses for preloading critical resources.

15. Page Rules & Config Rules

Page Rules let you customize behavior per URL pattern:

// Cache static assets aggressively
URL: example.com/assets/*
Cache Level: Cache Everything
Edge Cache TTL: 1 month
Browser Cache TTL: 1 year

// Bypass cache for admin area
URL: example.com/admin/*
Cache Level: Bypass
Security Level: High

// Force HTTPS on all pages
URL: http://example.com/*
Setting: Always Use HTTPS

Config Rules (newer) offer the same functionality without the 3-rule free-plan limit. Migrate Page Rules to Config Rules when possible.

16. Cloudflare Workers

Workers let you run JavaScript at the edge (before the request reaches your origin):

// Worker: Add security headers to all responses
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  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', 'camera=(), microphone=(), geolocation=()');
  newHeaders.set('Content-Security-Policy', "default-src 'self'; script-src 'self'");

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHeaders
  });
}

Free plan: 100,000 requests/day. Workers are ideal for A/B testing, redirects, header injection, authentication and serverless APIs.

17. Zero Trust & Access

Cloudflare Access (part of Zero Trust) adds identity-aware authentication in front of any internal app:

  • Protect admin panels, staging sites and internal dashboards without a VPN.
  • Integrate with identity providers: Google Workspace, GitHub, Okta, Azure AD, one-time PIN.
  • Define access policies: only users from @yourcompany.com can access admin.example.com.
  • Available on the free plan (50 users).

18. Email Security (DMARC / SPF / DKIM)

Cloudflare DNS makes it easy to add email authentication records that prevent domain spoofing:

// SPF record — authorize only your email provider to send
TXT  @  "v=spf1 include:_spf.google.com ~all"

// DKIM — add the TXT record provided by your email provider
TXT  google._domainkey  "v=DKIM1; k=rsa; p=MIIBIj..."

// DMARC — policy for handling failures
TXT  _dmarc  "v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com; pct=100"

Cloudflare also offers Email Routing (free forwarding) and Email Security (enterprise anti-phishing).

19. Monitoring & Analytics

  • Security Events — View every WAF block, challenge and rate-limit event with request details.
  • Analytics — Traffic, cached vs. uncached requests, bandwidth saved, threat overview.
  • Web Analytics — Privacy-friendly analytics (no cookies) that runs at the edge.
  • Notifications — Set up alerts for DDoS attacks, SSL expiration, origin errors.
  • Logpush (Enterprise) — Stream logs to S3, Datadog, Splunk, Elastic for long-term analysis.

20. 7-Day Quick Start Plan

  1. Day 1 — DNS & TLS: Add site to Cloudflare, delegate name servers, enable DNSSEC, set SSL to Full (Strict).
  2. Day 2 — WAF: Enable managed rules, turn on Bot Fight Mode.
  3. Day 3 — Rate Limiting: Add rules for login, API and contact form endpoints.
  4. Day 4 — Origin Hardening: Restrict origin to Cloudflare IPs, install Origin Certificate, enable Authenticated Origin Pulls.
  5. Day 5 — Caching: Configure Page Rules for static assets, bypass for dynamic/admin pages.
  6. Day 6 — Test & Tune: Run security scans, review Security Events, fix false positives.
  7. Day 7 — Document & Automate: Document all rules, set up notifications, schedule monthly reviews.

21. Troubleshooting

  • Error 521 (Web server is down) — Your origin server is not responding. Check if it's running and allows Cloudflare IPs.
  • Error 522 (Connection timed out) — Cloudflare can't reach your origin. Check firewall, verify port 443 is open.
  • Error 525 (SSL handshake failed) — Origin certificate mismatch. Use Full (not Strict) temporarily and fix the cert.
  • Error 526 (Invalid SSL certificate) — Origin cert is self-signed or expired in Strict mode. Install a valid cert or Cloudflare Origin Certificate.
  • Legitimate users blocked — Check Security Events, identify the blocking rule, create an exception.
  • DNS not propagated — Wait up to 48 hours. Verify with dig NS yourdomain.com.
  • Mixed content warnings — Enable Automatic HTTPS Rewrites and fix hard-coded HTTP URLs in your code.

22. Production Checklist

  • ☐ Name servers delegated to Cloudflare and confirmed active
  • ☐ DNSSEC enabled + DS record added at registrar
  • ☐ SSL/TLS set to Full (Strict)
  • ☐ Always Use HTTPS enabled
  • ☐ HSTS enabled with appropriate max-age
  • ☐ WAF managed rules enabled
  • ☐ Bot Fight Mode enabled
  • ☐ Rate limiting on login/API endpoints
  • ☐ Origin server accepts only Cloudflare IPs
  • ☐ Authenticated Origin Pulls or secret header configured
  • ☐ SPF, DKIM and DMARC records added
  • ☐ Page Rules / Config Rules for caching set up
  • ☐ Security Events reviewed (no unexpected blocks)
  • ☐ Notifications configured for DDoS and errors
  • ☐ Monthly rule review scheduled

23. FAQ

Is Cloudflare free?

Yes. The free plan includes DNS, CDN, basic DDoS protection, 5 Page Rules, Bot Fight Mode and limited WAF rules. Most small-to-medium sites run perfectly on the free plan.

Does Cloudflare slow down my site?

No — it almost always makes it faster. Cached content is served from the nearest edge node, reducing latency. The only possible slowdown is the initial 5-second challenge in "Under Attack" mode, which only activates during active DDoS attacks.

Can attackers bypass Cloudflare?

If your origin IP is exposed (in DNS records, email headers, error pages), attackers can connect directly. Harden your origin by allowing only Cloudflare IPs and hiding your real IP.

Should I use Flexible SSL?

Avoid it. Flexible SSL leaves the Cloudflare-to-origin connection unencrypted. Use Full (Strict) with a valid origin certificate (or a free Cloudflare Origin Certificate).

Does Cloudflare work with any hosting provider?

Yes. Cloudflare works with any origin server that can be reached via HTTP/HTTPS — AWS, DigitalOcean, Hetzner, shared hosting, VPS, on-premises, etc.

Will Cloudflare affect my SEO?

Positively. Faster load times, HTTPS by default, and better uptime (DDoS protection) all improve SEO signals. Cloudflare does not modify your HTML content (unless you enable Auto Minify or Workers).

24. Glossary

CDN
Content Delivery Network — a distributed network of servers that caches and serves content from locations close to the user.
DNSSEC
DNS Security Extensions — cryptographic signatures on DNS records to prevent spoofing and cache poisoning.
WAF
Web Application Firewall — inspects HTTP requests and blocks known attack patterns (SQLi, XSS, etc.).
DDoS
Distributed Denial of Service — an attack that floods a server with traffic to make it unavailable.
Edge
The network of servers closest to end users where Cloudflare processes and caches requests.
Origin
Your actual web server that hosts the application or website content.
HSTS
HTTP Strict Transport Security — a header that tells browsers to always use HTTPS for your domain.
Zero Trust
A security model where no user or device is trusted by default, even inside the corporate network.
Workers
Cloudflare's serverless execution environment that runs JavaScript at the edge.
SPF / DKIM / DMARC
Email authentication protocols that verify sender identity and prevent domain spoofing.

25. References

26. Conclusion

Cloudflare is one of the most effective tools you can put in front of any domain. Even on the free plan, you get DNS, CDN, DDoS protection, basic WAF and automatic TLS — a security and performance upgrade that takes less than 30 minutes to set up.

Follow the 7-day plan, harden your origin, monitor Security Events, and iterate. Each layer you add (DNSSEC, WAF rules, rate limiting, origin restrictions) makes your domain significantly more resilient.

Add your domain to Cloudflare today, enable Full (Strict) SSL and DNSSEC, and review your first Security Events report within 24 hours.