
August 22, 2026
11 min read
Table of Contents
By Kokil Thapa | Last reviewed: August 2026
Getting Cloudflare CDN setup and best practices right is the difference between a site that loads instantly worldwide and one that breaks authentication or serves stale content to logged-in users. I have configured Cloudflare for dozens of production Laravel, WordPress, and custom PHP applications serving clients in Nepal and globally, where bandwidth costs are high and latency to international servers can be punishing. This guide covers the exact configuration steps, cache rules, and security settings that work in real production environments, avoiding the common pitfalls that cause more problems than they solve.
Before touching any Cloudflare settings, ensure your application architecture supports a reverse proxy. For developers building modern web systems, understanding how your framework handles trusted proxies is critical; my article on Laravel API best practices covers the backend trust configuration necessary when sitting behind a CDN. Without this, your application will see Cloudflare’s IP addresses instead of real user IPs, breaking rate limiting, geolocation, and audit logs.
How do you configure Cloudflare CDN setup and best practices for SSL and DNS?
The most frequent production outages I encounter during Cloudflare migrations stem from incorrect SSL mode selection. Cloudflare offers four SSL/TLS encryption modes, and choosing the wrong one creates either security vulnerabilities or infinite redirect loops.
Selecting the correct SSL/TLS encryption mode
- Off: Never use this in production. Traffic between Cloudflare and your origin travels unencrypted.
- Flexible: Avoid unless your origin absolutely cannot support HTTPS. This mode causes redirect loops with Laravel, WordPress, and most modern frameworks that enforce HTTPS via middleware or HSTS.
- Full: Encrypts traffic end-to-end but does not validate the origin certificate. Acceptable if your origin uses a self-signed certificate or an expired Let's Encrypt cert.
- Full (Strict): The only recommended setting for production in 2026. Requires a valid, unexpired certificate on the origin that matches the hostname. Use Cloudflare Origin CA certificates (free, 15-year validity) or Let's Encrypt.
On every Laravel and WordPress project I manage, I set SSL/TLS to Full (Strict) immediately after adding the site. This prevents man-in-the-middle attacks between Cloudflare and your origin server while avoiding the redirect loop hell of Flexible mode.
DNS record configuration and proxy status
When adding DNS records, the orange cloud (Proxied) vs. grey cloud (DNS Only) distinction matters enormously. Only HTTP/HTTPS traffic should be proxied through Cloudflare. FTP, SSH, SMTP, and database ports must remain DNS-only or Cloudflare will drop the connections.
<!-- Example DNS configuration for a Laravel app -->
Type Name Content Proxy Status TTL
A @ 203.0.113.50 Proxied Auto
A www 203.0.113.50 Proxied Auto
A mail 203.0.113.50 DNS Only Auto
A ftp 203.0.113.50 DNS Only Auto
TXT @ v=spf1 include:_spf.google.com ~all For Nepali businesses hosting on shared infrastructure or local VPS providers, proxying your primary domain through Cloudflare provides DDoS protection and masks your origin IP address—a critical security measure given the increasing frequency of automated attacks targeting South Asian hosting infrastructure. If you're evaluating hosting options alongside CDN setup, review cloud hosting services in Nepal to understand which providers integrate cleanly with Cloudflare's proxy layer.
What cache rules prevent stale content in dynamic applications?
Caching is where most Cloudflare configurations fail for dynamic sites. The default "Standard" caching level caches static assets (CSS, JS, images) but respects origin cache headers for HTML. However, many frameworks send aggressive cache headers that conflict with Cloudflare's behavior, or omit them entirely, causing unpredictable results.
Configuring Cache Rules for Laravel and PHP applications
In 2026, Cloudflare's Cache Rules (replacing legacy Page Rules for new zones) provide granular control. Create these rules in order of priority:
- Bypass cache for authenticated users: Match cookie presence (
laravel_session,XSRF-TOKEN,wordpress_logged_in_*) and set Cache Level to Bypass. This prevents serving cached pages to logged-in users. - Bypass cache for admin/API routes: Match URI path prefixes
/admin/*,/api/*,/dashboard/*,/wp-admin/*. Set Cache Level to Bypass. - Cache static assets aggressively: Match file extensions
.css, .js, .png, .jpg, .webp, .woff2, .svg. Set Cache TTL to 1 month, enable Browser Cache TTL override. - Cache public HTML pages cautiously: For marketing pages, blog posts, or legal information sites like court marriage portals I've built, match specific URI patterns and set Cache TTL to 1 hour with "Respect Origin Headers" enabled.
# Example Cache Rule expression (Cloudflare Dashboard > Rules > Cache Rules)
# Rule 1: Bypass for authenticated sessions
(http.cookie contains "laravel_session") or
(http.cookie contains "wordpress_logged_in") or
(http.cookie contains "XSRF-TOKEN")
# Action: Cache Level = Bypass
# Rule 2: Aggressive static asset caching
(http.request.uri.path.extension in {"css" "js" "png" "jpg" "webp" "woff2" "svg"})
# Action: Edge Cache TTL = 1 month, Browser Cache TTL = 1 month A common mistake I see on client projects is caching HTML responses that contain CSRF tokens or user-specific data. This breaks form submissions and exposes session data. Always test cache behavior with both authenticated and unauthenticated browser profiles before going live.
Understanding Cache-Control header interactions
Cloudflare respects Cache-Control: private, no-store, and no-cache directives by default. If your Laravel application sends Cache-Control: no-cache, private for all responses (the framework default for web routes), Cloudflare won't cache HTML regardless of your Cache Rules. Override this selectively for public content by setting explicit cache headers in your controllers or middleware:
// Laravel controller for public blog post
return response($view)
->header('Cache-Control', 'public, max-age=3600')
->header('Vary', 'Accept-Encoding'); For WordPress sites, plugins like WP Rocket or Cloudflare's official plugin handle these headers automatically. On custom Laravel builds, you must manage them explicitly. My experience maintaining legal-tech portals with sensitive document workflows has taught me to default to private, no-cache for any route handling personal data, then selectively opt-in public pages to caching.
| Content Type | Recommended Edge TTL | Browser TTL | Purge Strategy |
|---|---|---|---|
| Static assets (CSS/JS/images) | 1 month | 1 month | Versioned filenames or manual purge on deploy |
| Public HTML (blog, landing pages) | 1 hour – 24 hours | 10 minutes | Purge on content update via API or plugin |
| Authenticated/user-specific pages | Bypass | Bypass | N/A |
| API JSON responses | Bypass or 1 min | 0 seconds | Event-driven invalidation |
| Admin/dashboard routes | Bypass | Bypass | N/A |
How do you secure applications with Cloudflare WAF and bot management?
Security is where Cloudflare delivers immediate ROI beyond performance. For Nepali businesses facing increasing automated attack traffic, proper WAF configuration blocks credential stuffing, SQL injection, and scraper bots before they reach your origin server.
Enabling and tuning Managed WAF rulesets
Cloudflare's Managed Rulesets (OWASP Core Ruleset + Cloudflare Specials) should be enabled on all production zones. Start with "Log" mode for two weeks to identify false positives, then switch to "Block" or "Challenge". Common false positives I encounter include:
- Payment gateway callbacks (eSewa, Khalti, ConnectIPS) flagged as suspicious POST requests
- File upload endpoints for legal document submission triggering multipart body inspection rules
- API webhook receivers from third-party services blocked by rate-limiting rules
Create WAF exceptions for known legitimate sources rather than disabling rules globally. For example, whitelist eSewa's callback IP range for your payment confirmation endpoint while keeping the rule active elsewhere.
Bot Fight Mode and Super Bot Fight Mode
Enable Bot Fight Mode (free tier) on all sites. It challenges requests with low JavaScript scores, blocking automated scrapers and credential stuffers without impacting real users. For eCommerce sites processing transactions, upgrade to Super Bot Fight Mode (Pro plan) which distinguishes between verified bots (Googlebot, payment processors) and suspicious automation.
On legal service portals I maintain, bot traffic attempting to scrape attorney directories or submit spam contact forms dropped by 80-90% after enabling Bot Fight Mode. The key metric to monitor is "Managed Challenge" pass rate—if legitimate users are failing challenges at more than 2%, review your WAF exception list.
Which performance optimizations deliver measurable speed improvements?
Beyond caching, Cloudflare's performance features reduce Time to First Byte (TTFB) and Largest Contentful Paint (LCP)—metrics that directly impact SEO rankings and conversion rates. These settings apply universally across Laravel, WordPress, and custom PHP stacks.
Compression and protocol optimization
Enable Brotli compression in Speed > Optimization. Brotli achieves 15-25% better compression ratios than gzip for text-based assets (HTML, CSS, JS). All modern browsers support it as of 2026. Keep gzip enabled as fallback for legacy clients.
Enable HTTP/3 (QUIC) and Early Hints (103). QUIC reduces connection establishment latency, especially beneficial for users on mobile networks in Nepal where TCP handshakes suffer from packet loss. Early Hints allow Cloudflare to send Link headers before your origin responds, letting browsers preload critical resources while PHP processes the request.
Image optimization and Polish
For sites serving product images (eCommerce florist shops, travel galleries), enable Cloudflare Polish (Pro plan) to automatically convert JPEG/PNG to WebP/AVIF and strip EXIF metadata. Pair this with responsive <picture> tags in your Blade templates or WordPress themes to serve appropriately sized images.
If budget constraints prevent upgrading to Pro, use build-time image optimization with Vite or Sharp library in Laravel, then let Cloudflare cache the pre-optimized assets. This achieves 80% of the benefit at zero additional cost.
Argo Smart Routing for international audiences
For Nepali businesses serving diaspora customers in Australia, US, or UK (common for gift card platforms, grocery delivery, and legal services), Argo Smart Routing reduces cross-border latency by 30% on average. It routes traffic through Cloudflare's private backbone instead of public internet peering points. At $5/month + usage, it's cost-effective for sites where international conversion rates justify the expense.
How do you troubleshoot common Cloudflare integration failures?
Even with correct configuration, production issues arise. These are the problems I diagnose most frequently on client deployments.
Infinite redirect loops after enabling Cloudflare
This almost always indicates SSL mode mismatch. If your Laravel app enforces HTTPS via URL::forceScheme('https') or TrustProxies middleware, but Cloudflare is set to Flexible SSL, Cloudflare connects to your origin over HTTP. Your app redirects to HTTPS, Cloudflare receives the redirect, connects over HTTP again, and loops forever.
Fix: Set SSL to Full (Strict). Ensure your origin has a valid certificate. In Laravel, configure TrustProxies middleware to trust Cloudflare's IP ranges:
// app/Http/Middleware/TrustProxies.php
protected $proxies = '*'; // Or specific Cloudflare IP ranges
protected $headers = \Illuminate\Http\Request::HEADER_X_FORWARDED_FOR |
\Illuminate\Http\Request::HEADER_X_FORWARDED_HOST |
\Illuminate\Http\Request::HEADER_X_FORWARDED_PORT |
\Illuminate\Http\Request::HEADER_X_FORWARDED_PROTO |
\Illuminate\Http\Request::HEADER_X_FORWARDED_AWS_ELB; Stale content served to authenticated users
If logged-in users see cached versions of pages meant for guests, your cache bypass rules aren't matching correctly. Verify cookie names match exactly (Cloudflare string matching is case-sensitive). Test with Cloudflare's "Cache Everything" page rule disabled—this overrides standard cache behavior and ignores cookies unless explicitly excluded.
Origin server IP exposure despite proxying
If attackers discover your real server IP, they can bypass Cloudflare entirely. Prevent this by configuring your firewall (UFW on Ubuntu) to accept HTTP/HTTPS traffic only from Cloudflare's published IP ranges. Reject all other inbound traffic on ports 80/443. This ensures all web traffic must traverse Cloudflare's security layer.
For teams managing multiple sites across Nepal and international markets, integrating Cloudflare into your deployment workflow pays dividends. If you're building infrastructure for a growing business, consider reviewing why every Nepali business should use CDN for speed to align technical decisions with local market realities.
Implementing Cloudflare CDN Setup and Best Practices for Production Reliability
Effective Cloudflare CDN setup and best practices come down to three principles: encrypt everything with Full (Strict) SSL, cache selectively based on authentication state and content type, and layer security controls from bot detection through WAF to origin firewall. Treat Cloudflare as part of your application architecture, not a bolt-on optimization. Test every configuration change in staging first, monitor analytics for false positives, and document your cache rules alongside your application code.
If you need help configuring Cloudflare for a Laravel, WordPress, or custom PHP application—or diagnosing why your current setup isn't delivering expected performance and security gains—get in touch. I regularly audit and optimize CDN configurations for production systems serving Nepali and global audiences.

