Sandaruwan Jayasundara home

Cloudflare, WAF, and Web Application Security Best Practices

Application-layer security isn't just input validation — the network edge in front of your app is where most attacks are stopped or missed. Here's how I configure Cloudflare and a WAF for production apps.

Sandaruwan Jayasundara · Updated October 23, 2026 · 6 min read

A well-written application is still exposed if the edge in front of it isn't configured. Cloudflare and a properly tuned WAF handle an entire class of attacks before they ever reach your servers.

In short: proxy your traffic through Cloudflare, lock the origin so it only accepts traffic from Cloudflare, enable the managed WAF rules, add rate limits on authentication endpoints, and set security headers in the application. Then keep fixing access control and input handling in your own code, because a WAF cannot see business logic.

Key takeaways

  • An edge WAF is only effective if attackers cannot bypass it by hitting the origin IP directly.
  • Roll out new rules in log mode, review the matches, then switch to block.
  • Rate-limit login, signup, password reset, and other expensive endpoints first.
  • Never cache authenticated or personalized responses at the edge.
  • Broken access control and logic bugs are application problems; no WAF rule fixes them.

1. DNS and Proxy Setup

  • Proxy (orange-cloud) all public-facing DNS records so origin IPs stay hidden
  • Enforce "Full (strict)" SSL mode with a valid origin certificate — never "Flexible" in production
  • Restrict origin server firewall rules to Cloudflare's published IP ranges

Hiding the origin is the step most often skipped, and without it the WAF is optional for attackers. Old DNS records, mail servers on the same IP, and historical DNS lookups can all reveal an origin address. Two stronger options than an IP allow list are Cloudflare Tunnel, where the server makes an outbound connection and needs no open inbound ports, and authenticated origin pulls, where the origin only accepts connections presenting Cloudflare's client certificate. If an origin IP has been exposed in the past, change it after locking things down.

2. WAF Rules That Matter Most

  • Enable managed rulesets (OWASP core rules) as a baseline against common exploits
  • Custom rules blocking known bad user agents, suspicious query patterns, and known scanner signatures
  • Geo-based or ASN-based challenge rules if attack traffic clusters from specific sources
  • Log mode first for new rules — verify no false positives before switching to block
Turn on WAF rules in "log" mode before "block" mode. A misconfigured rule that blocks real users is worse than the attack it was meant to stop.

Custom rules use Cloudflare's rules language. Two examples I find useful on almost every site: blocking probes for files that should never be requested, and restricting an admin area to known networks.

# Rule 1 — action: Block
(http.request.uri.path contains "/.env")
or (http.request.uri.path contains "/.git/")
or (http.request.uri.path contains "/wp-login.php" and not http.host eq "blog.example.com")

# Rule 2 — action: Block (or Managed Challenge)
(starts_with(http.request.uri.path, "/admin")
 and not ip.src in {203.0.113.0/24 198.51.100.7})

Keep custom rules few and specific. Broad rules based on user agent strings or countries catch real users and are easy for attackers to evade; managed rulesets are maintained against current exploits and should do most of the work.

3. Rate Limiting

  • Strict limits on login, signup, and password-reset endpoints — the most common brute-force targets
  • Looser, monitored limits on general API traffic to absorb legitimate bursts
  • Rate limit by a combination of IP and route, not IP alone — shared corporate IPs shouldn't get blanket-blocked

Keep a second, application-level limit as well, keyed by account or API key rather than IP. Edge limits stop floods; application limits stop a single logged-in user or leaked API key from abusing an expensive endpoint. In an Express API this is a middleware on the relevant routes, as described in the Node.js and Express API architecture guide.

4. Bot Management

Not all bots are hostile — legitimate crawlers (Googlebot, Bingbot, and AI crawlers like GPTBot and ClaudeBot) need to reach your content for SEO and discoverability. Configure bot rules to challenge or block credential-stuffing and scraping bots specifically, rather than blanket-blocking all automated traffic.

5. Security Headers at the Application Layer

Strict-Transport-Security: max-age=63072000; includeSubDomains
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin

These headers stop entire attack classes (clickjacking, MIME sniffing, some XSS vectors) for effectively zero runtime cost.

Content Security Policy is the one that needs care. A strict policy will break third-party scripts, analytics, and inline styles you forgot about. Deploy it first as Content-Security-Policy-Report-Only, collect violation reports, adjust, and then enforce. Add frame-ancestors 'none' (or 'self') to cover clickjacking, and set cookies with Secure, HttpOnly, and SameSite.

Caching Without Leaking Data

Edge caching improves speed and absorbs load, but a wrong cache rule can serve one user's page to another. Cache static assets aggressively with hashed filenames; bypass the cache for /api/*, authenticated pages, and any response that sets cookies. Send explicit Cache-Control: private, no-store on personalized responses so a later rule change cannot cache them by accident.

6. DDoS Protection

Cloudflare's network-level DDoS mitigation is largely automatic once traffic is proxied — the engineering work is making sure origin servers aren't directly reachable, and that rate limiting protects expensive endpoints (search, uploads, report generation) that a volumetric attack would target specifically.

What a WAF Does Not Protect Against

Threat Edge / WAF Where it is really fixed
Volumetric DDoSStrongEdge, plus a hidden origin
Known exploit payloads (SQLi, XSS patterns)GoodParameterized queries, output encoding
Credential stuffingPartialRate limits, MFA, breached-password checks
Broken access control (IDOR)NoneAuthorization checks in the service layer
Business logic abuseNoneDomain validation and tests
Vulnerable dependencies, leaked secretsMinimalDependency scanning, secrets management in CI/CD

Session and token handling sits firmly on the application side; see JWT vs session authentication for those trade-offs, and DevOps for full stack developers for scanning and secrets in the pipeline.

Monitoring and Incident Response

  • Review the security events log weekly at first: which rules fire, on which paths, and whether any hits are real users.
  • Alert on sudden changes in blocked requests or origin error rates, not on every individual block.
  • Keep a short runbook: how to enable "I'm Under Attack" mode, tighten a rate limit, or block a path in minutes.
  • Treat emergency settings as temporary and remove them once the incident is over, because they add friction for every visitor.

Production Checklist

  1. All public records proxied; SSL mode Full (strict); HSTS enabled.
  2. Origin reachable only through Cloudflare (allow list, Tunnel, or authenticated origin pulls).
  3. Managed WAF rules on; custom rules tested in log mode first.
  4. Rate limits on auth and expensive endpoints, at the edge and in the app.
  5. Security headers and a CSP rolled out via report-only.
  6. Cache bypass for APIs and authenticated pages.
  7. Verified search engine bots allowed; abusive bots challenged.
  8. Security events reviewed and a runbook written.

Bringing It Together

Edge security and application security are complementary, not interchangeable — a WAF catches what your code shouldn't have to, and your code should never assume the WAF caught everything. I configure both layers together as part of any production deployment.

Frequently Asked Questions

Is Cloudflare's WAF enough to secure a web application?

No. A WAF blocks known attack patterns, floods, and abusive bots at the edge, but it cannot detect broken access control, business logic flaws, or vulnerable dependencies. Application-level authorization, validation, and secure coding are still required.

Which Cloudflare SSL mode should I use?

Full (strict), with a valid certificate on the origin such as a Cloudflare Origin CA certificate. Flexible mode leaves traffic between Cloudflare and your server unencrypted and should not be used in production.

How do I stop attackers from bypassing Cloudflare?

Make the origin reachable only through Cloudflare: allow only Cloudflare IP ranges in the origin firewall, or use Cloudflare Tunnel or authenticated origin pulls. If the origin IP was exposed before, change it after locking it down.

Which endpoints should be rate limited first?

Login, signup, password reset, and OTP verification endpoints, followed by expensive operations such as search, file uploads, and report generation. Combine edge limits by IP and path with application limits by account or API key.

Will Cloudflare bot rules block Google from crawling my site?

Not if configured carefully. Allow verified bots such as Googlebot and Bingbot, and target challenges at credential stuffing and scraping behaviour rather than blocking all automated traffic.

I'm Sandaruwan Jayasundara — Senior Software Engineer | Cloud & DevOps. See AWS cloud architecture for startups or get in touch about securing your infrastructure. Security setup is part of my full-stack development services.

Related articles

Need help with your project?

I take on a limited number of remote engagements. Explore my services or get in touch.

Contact Sandaruwan