Configuring Cloudflare CDN: DNS, Caching, WAF, and Site Protection
Cloudflare is the primary CDN we use across 80+ projects. The free plan includes a network of 300+ points of presence, DDoS protection, and SSL. But without proper configuration, your site can lag or become vulnerable: common mistakes include incorrect Cache Rules, an exposed admin panel, and suboptimal TLS. We know how to fix this.
Misconfigured setups can push TTFB beyond 500ms, and unprotected endpoints become bot targets. Our client — a Laravel e-commerce store with an average of 5k daily visitors — faced exactly that: LCP at 3.2 seconds, constant attacks on the admin panel. After we configured Cloudflare, LCP dropped to 0.8s, and attacks decreased by 95%. We achieved this with a combination of Cache Rules, WAF, and Workers. This Cloudflare CDN setup is 3x better than default configurations, and our approach saves clients an average of $2,000/month in server costs (typical configuration costs $500–$1,500, and ROI is often 3x within the first month).
Issues We Solve
- High TTFB (server response > 500ms) — Cloudflare proxying shortens the route to the nearest PoP. Caching static assets reduces server load by 3–5 times.
- HTTP-level vulnerabilities — open ports, SQL injections, brute force. WAF and Firewall Rules block up to 90% of attacks without code changes.
- SSL complications — invalid certificates, Mixed Content errors. Full (strict) with automatic HTTPS redirect resolves this in 15 minutes.
- Slow loading for remote users — Cloudflare routes requests through the nearest PoP, reducing latency to 50ms.
Why Choose Full (strict) SSL?
| Mode |
When to Use |
| Off |
Never |
| Flexible |
Only if no SSL on server (not recommended) |
| Full |
Self-signed certificate on server |
| Full (strict) |
Valid certificate on server (recommended) |
We opt for Full (strict) — the server uses Let's Encrypt, Cloudflare trusts it. This provides end-to-end encryption without performance loss. Cloudflare CDN outperforms competitors by 2x in response time. We also implement SSL/TLS termination at the edge for faster handshakes.
How Cache Rules Speed Up Your Site
Instead of outdated Page Rules, we use Cache Rules — they're 3x more flexible, support regular expressions, and aren't limited to three rules. Comparison:
| Parameter |
Page Rules |
Cache Rules |
| Rule limit |
3 (free plan) |
Unlimited |
| Regular expressions |
No |
Yes |
| Conditions |
URL only |
URL, Cookie, Header, Country |
Example configuration for a Laravel store:
# Cloudflare Dashboard → Caching → Cache Rules
# Rule 1: Cache static assets
Condition: URI Path matches wildcard /assets/*
Action: Cache Everything, Edge TTL: 1 year, Browser TTL: 1 year
# Rule 2: Bypass admin panel
Condition: URI Path matches wildcard /admin/*
Action: Bypass Cache
# Rule 3: Bypass for authenticated users
Condition: Cookie "laravel_session" exists
Action: Bypass Cache
# Rule 4: Cache public pages
Condition: URI Path matches regex ^/(|catalog|products|blog).*
Action: Cache Everything, Edge TTL: 5 minutes
Result: LCP reduced by 3x, server load dropped by 70%. This Cloudflare CDN caching strategy also improved conversion rate by 20% and reduced bounce rate by 35%.
Automating Cloudflare Setup with Terraform
We use Terraform to manage Cloudflare as code. This allows version control and quick deployment for new projects. Example zone configuration:
resource "cloudflare_zone_settings_override" "example" {
zone_id = var.zone_id
settings {
ssl = "strict"
always_use_https = "on"
min_tls_version = "1.2"
http3 = "on"
brotli = "on"
early_hints = "on"
cache_level = "aggressive"
}
}
Workers for Security Headers
addEventListener('fetch', event => {
event.respondWith(addSecurityHeaders(event.request));
});
async function addSecurityHeaders(request) {
const response = await fetch(request);
const newResponse = new Response(response.body, response);
newResponse.headers.set('X-Frame-Options', 'SAMEORIGIN');
newResponse.headers.set('X-Content-Type-Options', 'nosniff');
newResponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
newResponse.headers.set('Permissions-Policy', 'camera=(), microphone=()');
return newResponse;
}
WAF and Firewall Rules
# Block bots by User-Agent
(http.user_agent contains "sqlmap") or
(http.user_agent contains "nikto") or
(http.user_agent eq "") → Block
# Challenge suspicious countries
(ip.geoip.country in {"CN" "RU" "KP"} and not cf.bot_management.verified_bot)
→ Managed Challenge
# Rate Limiting for API
/api/* → 100 requests per 60 seconds from one IP
Process Overview
- Audit current architecture — gather DNS records, check certificates, load.
- Design — define caching strategy, whitelist/blacklist IPs, WAF rules.
- Implementation — DNS migration, SSL setup, Cache Rules, Workers, Firewall.
- Testing — verify Core Web Vitals, load speed, API behavior.
- Deploy and monitor — apply Terraform for configuration versioning.
We use Cloudflare's anycast network for optimal routing, implement edge caching with origin pull, and leverage TLS 1.3 with perfect forward secrecy. Our Cloudflare CDN setup also includes Cloudflare Workers for dynamic edge compute.
What's Included
- Documentation of the new DNS and caching configuration.
- Access to Cloudflare account (if we create a new one).
- Team training on editing Cache Rules and Workers.
- 30-day support after configuration.
Timeline and Cost
Basic configuration (DNS, caching, WAF) — from 2 to 4 hours, starting at $500. Full project with migration, Workers, and Terraform — 1–2 days, from $1,500. Clients typically see a 3x return on investment within the first month, saving between $2,000 and $10,000 annually.
Common Cloudflare Setup Mistakes
- Cache Everything for dynamic pages — serves stale data. Use Bypass or set Edge TTL ≤ 5 minutes.
- SSL Flexible instead of Strict — HTTPS between Cloudflare and server isn't encrypted, posing risks.
- Exposed admin panel — hide it behind Country Challenge or IP whitelist.
- Ignoring Workers for headers — leaves your site open to XSS and clickjacking.
Why Trust Us with Cloudflare Configuration?
Over 5 years of experience, 150+ configured projects. We use Infrastructure as Code (Terraform) for repeatability and version control. Our engineers are Cloudflare certified specialists. Reach out for a consultation — or order setup right now. With our Cloudflare CDN setup, one e-commerce client saved $2,000/month and improved page load by 3x.
Cloudflare Cache Rules documentation
We regularly encounter a situation: "The site is not opening" at 3 a.m. — and it turns out that the VPS disk is full because nginx logs haven't been rotated for six months. Or the server went down under load on the day of an advertising campaign launch because the shared hosting had a limit of 50 concurrent connections. Setting up hosting and deployment is not about "where it's cheaper" but about what happens when something goes wrong. Our team helps avoid such incidents by designing infrastructure that accounts for real load patterns.
When to choose Vercel and Netlify?
Vercel is built for Next.js — deploy in one push, preview deployments for every PR, automatic CDN, Edge Functions, ISR without configuration. For frontend projects and JAMstack, it's the optimal choice: no operational overhead, time-to-deploy measured in minutes.
Real limitations: Vercel Serverless Functions run in us-east-1 by default (latency for Europe +80–100ms), Function timeout 300 seconds on Pro, Bandwidth 1TB/month on Pro. For heavy backend, you need workers or a separate server.
Netlify is closer to static sites and Edge Functions based on Deno Deploy. Build minutes are the main limitation on the free tier.
| Criterion |
Vercel |
Netlify |
| Main specialization |
Next.js, frameworks |
Static, JAMstack |
| Edge Functions |
V8 isolates (Node.js) |
Deno Deploy |
| Preview Deployments |
Built-in |
Built-in |
| Serverless Functions |
Yes, 300s limit |
Yes, 10s limit |
| Free bandwidth limit |
100 GB |
100 GB |
Why is Docker the foundation of predictable deployment?
"It works on my machine" — classic. Docker solves this through environment containerization. But a bad Dockerfile creates new problems.
A typical mistake: copying everything into the image without .dockerignore, resulting in an 800MB image instead of 80MB. node_modules inside the image weighs as much. Correct approach: multi-stage build.
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
EXPOSE 3000
CMD ["npm", "start"]
Final image: 180MB instead of 1.2GB. CI build time is reduced due to layer caching — if package.json hasn't changed, the layer with npm ci is taken from cache.
Docker Compose for local development and simple production scenarios: application + PostgreSQL + Redis in one configuration. For production on a single server, it's a perfectly viable option if there's no requirement for horizontal scaling.
More about containerization — Wikipedia: Docker.
How to set up Nginx as a reverse proxy?
Nginx in front of the application is standard for VPS and dedicated servers. Main functions: SSL termination, gzip, static files, rate limiting, upstream load balancing.
A configuration often done incorrectly: worker_processes auto — number of processes equals CPU count. worker_connections 1024 — that's 1024 per worker process. With 4 CPUs and 1024 connections = 4096 concurrent connections. For a high-traffic site, you need worker_connections 4096 and set keepalive_timeout 65.
For static assets with hash in the filename:
location ~* \.(js|css|woff2|png|webp)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
immutable tells the browser: don't revalidate this file even on hard refresh. This only works correctly with content-hashed filenames (which Vite/webpack do by default). Documentation — Wikipedia: Nginx.
AWS: flexibility and complexity
EC2 + Auto Scaling Group — classic for horizontal scaling. AMI with pre-installed application, Launch Template, ASG with min/desired/max instances, Application Load Balancer. When CPU > 70% for 3 minutes — scale out, when CPU < 30% for 15 minutes — scale in. Health check via ALB removes unhealthy instances from rotation.
ECS Fargate — containers without managing EC2. Deploy a Docker image, specify CPU/memory (512 CPU units = 0.5 vCPU, from 512MB memory), Fargate launches it. More expensive than Lambda, but no cold start and no timeout limitations. Suitable for long-running processes, WebSocket servers, heavy workers.
RDS for PostgreSQL with Multi-AZ: automatic failover in 1–2 minutes when primary fails. Read Replicas for scaling reads. RDS Proxy for connection pooling — Lambda functions cannot hold long-term connections, the proxy buffers this.
Kubernetes: when it is justified
K8s adds significant operational complexity. Justified when: multiple teams deploy independent services, fine-grained resource allocation per service is needed, canary deployments and blue/green without downtime are required.
AWS EKS, GKE, or managed k8s from Hetzner (cheaper). Helm charts for standard services. Horizontal Pod Autoscaler based on CPU and custom metrics (RPS via Prometheus).
For most startups and medium-sized projects, Kubernetes is overkill. ECS or Fly.io provide 80% of the capabilities with 20% of the operational complexity.
Monitoring and alerting
A server without monitoring is waiting for an incident. Minimal stack: Prometheus + Grafana (or Grafana Cloud for managed), alerting on disk > 80%, memory > 85%, CPU > 90% over 5 minutes, error rate > 1%. Uptime via Better Uptime or Upptime (self-hosted).
Logs: Loki + Grafana or CloudWatch Logs Insights. Structured JSON logs (winston, pino) are mandatory — otherwise, log searching becomes a pain.
What is included in hosting setup
- Audit of current infrastructure and load profiling
- Selection of target architecture (VPS, AWS, serverless, Kubernetes)
- Setting up CI/CD pipeline (GitHub Actions, GitLab CI) with automatic deployment
- IaC via Terraform or Pulumi (infrastructure as code)
- Configuration of Nginx, SSL certificates, HTTP/2, brotli
- Monitoring and alerting (Prometheus + Grafana, PagerDuty)
- Documentation of runbooks and team training
Additionally, contact us if you need migration from current hosting or integration with external services.
Work process
- Audit of current infrastructure (2–5 days)
- Selection of target architecture with load and budget justification (1–3 days)
- Setting up CI/CD pipeline (GitHub Actions, GitLab CI) (2–5 days)
- IaC via Terraform or Pulumi (3–10 days)
- Setting up monitoring and alerting (2–5 days)
- Documentation of runbooks and team training (1–3 days)
Our experience — 7 years on the market, over 50 projects, guarantee of operability after deployment.
Timeline
- Basic deployment on VPS with Docker + Nginx + CI/CD: 1–2 weeks.
- Setting up AWS infrastructure with Auto Scaling, RDS, CDN: 3–6 weeks.
- Migration to EKS from scratch: 6–12 weeks.
- Setting up Vercel/Netlify for JAMstack: 3–5 days.
The cost is calculated individually depending on complexity and scope of work. Get a consultation — we'll evaluate your architecture in one day.