Introduction
Why Cloudflare?
Cloudflare sits at the intersection of security, performance, and reliability. By acting as a reverse proxy for your public‑facing services, it can absorb DDoS attacks, enforce TLS, and cache static assets at edge locations worldwide. For production workloads, a well‑architected Cloudflare configuration reduces latency by up to 50 % and mitigates 99 % of common web threats.
Core Benefits
- Global Edge Network - Over 250 PoPs serve content close to users.
- Zero‑Trust Security - Integrated WAF, bot management, and access controls.
- Scalable CDN - Automatic caching and tiered cache policies.
- Programmable Edge - Cloudflare Workers let you run JavaScript at the edge.
This guide walks you through a production‑ready setup, from DNS delegation to automated infrastructure provisioning.
Architectural Overview
High‑Level Architecture
The diagram below illustrates the key components of a typical Cloudflare‑enabled production environment:
[Client] --> [Internet] --> [Cloudflare Edge (WAF, SSL, Workers)] --> [Load Balancer] --> [Origin Servers]
Components Explained
- DNS Zone - Cloudflare becomes the authoritative DNS server. All inbound traffic resolves to Cloudflare IPs.
- Edge Security Layer - Includes Web Application Firewall (WAF), Rate Limiting, Bot Fight Mode, and TLS 1.3 enforcement.
- Content Delivery Network - Static objects (images, CSS, JS) are cached at edge nodes. Dynamic content can be cached using custom rules.
- Cloudflare Load Balancer - Distributes traffic across multiple origins, providing health‑checks and automatic failover.
- Origin Pull - Cloudflare fetches uncached resources from your origin over a secure, private connection (origin certificates).
- Workers - Serverless scripts that can modify requests/responses, implement redirects, or add security headers on the fly.
Security Flow
- TLS Handshake - Terminated at Cloudflare using your custom certificate or Cloudflare‑issued Universal SSL.
- WAF Evaluation - Requests are inspected against OWASP‑based rulesets.
- Rate Limiting - Excessive requests from a single IP are throttled.
- Origin Request - Only legitimate traffic reaches the origin, signed with a client‑certificate for mutual TLS.
The architecture minimizes exposure of your real servers while delivering fast, cached content to end users.
Implementation Steps
Step 1 - DNS Migration
hcl
terraform/cloudflare.tf
resource "cloudflare_zone" "example" { zone = "example.com" }
resource "cloudflare_record" "app" { zone_id = cloudflare_zone.example.id name = "www" type = "CNAME" value = "example.com" proxied = true }
The proxied = true flag ensures traffic routes through Cloudflare's edge. After applying the configuration, update your domain registrar to point the NS records to the Cloudflare‑provided nameservers.
Step 2 - Enforcing TLS & Certificates
Create an Origin Certificate that Cloudflare can present to your origin server.
bash
Generate an Origin CA certificate via Cloudflare UI or API
curl -X POST "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/origin_ca/certificates"
-H "Authorization: Bearer $CF_API_TOKEN"
-H "Content-Type: application/json"
--data '{"hostnames":["example.com","*.example.com"],"requested_validity":3650,"request_type":"origin-rsa"}'
Install the returned certificate and private key on your web server and configure it to accept only TLS 1.2+ connections.
Step 3 - Configuring the WAF and Rate Limiting
hcl resource "cloudflare_firewall_rule" "sql_injection" { zone_id = cloudflare_zone.example.id description = "Block SQL injection attempts" filter { expression = "(http.request.uri.path contains "sql" or http.request.body contains "SELECT")" paused = false } action = "block" }
resource "cloudflare_rate_limit" "api_limit" { zone_id = cloudflare_zone.example.id match { request { url = "api.example.com/*" } threshold = 1000 period = 60 action { mode = "challenge" } } }
These rules protect against injection attacks and abusive API usage.
Step 4 - Setting Up Cloudflare Workers for Header Management
// workers/security-headers.js
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('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload') newHeaders.set('X-Content-Type-Options', 'nosniff') newHeaders.set('X-Frame-Options', 'DENY') newHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin') return new Response(response.body, { status: response.status, statusText: response.statusText, headers: newHeaders }) }
Deploy the script via the Cloudflare dashboard or using the wrangler CLI:
bash wrangler publish ./workers/security-headers.js --name security-headers
Associate the worker with a route, e.g., example.com/*.
Step 5 - Configuring Caching Policies
hcl resource "cloudflare_page_rule" "static_assets" { zone_id = cloudflare_zone.example.id target = "example.com/*.css" actions { cache_level = "cache_everything" edge_cache_ttl = 86400 browser_cache_ttl = 14400 } }
Create additional page rules for JavaScript, images, and PDFs, adjusting TTLs based on your update cadence.
Step 6 - Load Balancer with Health Checks
hcl resource "cloudflare_load_balancer" "app_lb" { zone_id = cloudflare_zone.example.id name = "app.example.com" fallback_pool = cloudflare_load_balancer_pool.primary.id default_pool = cloudflare_load_balancer_pool.primary.id
session_affinity = "sticky" ttl = 30 }
resource "cloudflare_load_balancer_pool" "primary" { zone_id = cloudflare_zone.example.id name = "primary-pool" origins = [{ name = "origin-1" address = "10.0.1.10" enabled = true }] monitor = cloudflare_load_balancer_monitor.http.id }
resource "cloudflare_load_balancer_monitor" "http" { zone_id = cloudflare_zone.example.id type = "http" method = "GET" path = "/healthcheck" timeout = 5 retries = 2 expected_body = "OK" }
The load balancer guarantees high availability by routing traffic away from unhealthy origins.
Step 7 - Monitoring and Alerts
Enable Cloudflare analytics dashboards and configure webhook alerts for security events. Terraform can provision webhook endpoints as part of your monitoring stack.
hcl resource "cloudflare_rule_set" "alert_rules" { zone_id = cloudflare_zone.example.id description = "Email alerts for critical WAF blocks" rules = [{ expression = "http.request.uri.path contains "/admin"" action = "log" enabled = true }] }
Pair this with a SIEM solution to ingest logs via Cloudflare Logpush.
FAQs
Frequently Asked Questions
Q1: Do I need to disable my origin server’s firewall once Cloudflare is in front?
A: No. Keep your origin firewall active and restrict inbound traffic to Cloudflare IP ranges only. This adds a second layer of protection and prevents direct attacks that bypass the CDN.
Q2: How does Cloudflare handle dynamic content that cannot be cached?
A: Dynamic responses bypass the cache unless you explicitly enable Cache‑Everything with appropriate Cache‑Tag or Cache‑Control headers. Workers can also add custom cache keys to selectively store dynamic fragments.
Q3: Can I use Cloudflare with containers or serverless platforms like AWS Lambda?
A: Absolutely. Cloudflare terminates TLS and forwards the request to your serverless endpoint via a private origin hostname. You can still benefit from the WAF, rate limiting, and Workers for request shaping.
Q4: What is the impact of enabling "Automatic HTTPS Rewrites"?
A: This feature rewrites insecure http:// URLs in HTML content to https://. It prevents mixed‑content warnings without requiring code changes, but be aware that it may break external dependencies that do not support HTTPS.
Q5: How do I test my configuration before pushing to production?
A: Use Cloudflare’s Staging mode (available with Enterprise) or create a sub‑domain (staging.example.com) that points to a duplicate origin. Apply the same Terraform modules and validate security events via the dashboard.
Conclusion
Bringing It All Together
A production‑ready Cloudflare deployment combines DNS delegation, strict TLS, a hardened WAF, granular rate limiting, programmable Workers, and intelligent load balancing. By codifying every component with Terraform, you achieve repeatable, version‑controlled infrastructure that can be promoted across environments with confidence.
Key takeaways:
- Security first - Turn on Universal SSL, enforce TLS 1.3, and lock down origins to Cloudflare IPs.
- Performance at scale - Leverage page rules and custom caching to keep latency low for both static and dynamic assets.
- Automation - Terraform modules, Cloudflare API, and Workers scripts keep the setup deterministic and audit‑ready.
- Observability - Enable Logpush, dashboard alerts, and SIEM integration to stay ahead of emerging threats.
Implementing the steps outlined in this guide equips your organization with a resilient edge layer that protects against attacks while delivering a seamless user experience worldwide.
