Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Cloudflare CDN Setup and Best Practices

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.

User BrowserHTTPS RequestCloudflare EdgeSSL TerminationWAF + Cache CheckDNS Only RecordsSSH / FTP / SMTPOrigin ServerFull (Strict) SSLHTTPSHTTPS (Encrypted)Direct TCP
Cloudflare CDN setup and best practices: SSL Full (Strict) mode with proxied HTTP traffic and DNS-only non-HTTP services

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:

  1. 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.
  2. Bypass cache for admin/API routes: Match URI path prefixes /admin/*, /api/*, /dashboard/*, /wp-admin/*. Set Cache Level to Bypass.
  3. 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.
  4. 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 TypeRecommended Edge TTLBrowser TTLPurge Strategy
Static assets (CSS/JS/images)1 month1 monthVersioned filenames or manual purge on deploy
Public HTML (blog, landing pages)1 hour – 24 hours10 minutesPurge on content update via API or plugin
Authenticated/user-specific pagesBypassBypassN/A
API JSON responsesBypass or 1 min0 secondsEvent-driven invalidation
Admin/dashboard routesBypassBypassN/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.

Incoming RequestIP + Headers + BodyBot Score CheckJS Challenge / BlockWAF Managed RulesOWASP + CustomRate LimitingPer-IP / Per-EndpointCache LookupHit / Miss / BypassOrigin ServerPHP-FPM / NodeBlock / ChallengeReturn 403 / 5xxPassCleanAllowedWithin LimitMiss/BypassNo Cache
Cloudflare security pipeline: bot detection, WAF rules, rate limiting, and cache evaluation before reaching origin

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.

User DeviceMobile / DesktopHTTP/3 QUICBrotli DecodeWebP RenderCloudflare EdgeBrotli CompressHTTP/3 + 103Polish (WebP)Argo RoutingOrigin ServerLaravel / WPRaw HTML/CSS/JSJPEG/PNG AssetsStandard TCPOptimizedUncompressed
Cloudflare performance stack: Brotli, HTTP/3, Polish, and Argo transform assets between origin and user

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.

Frequently Asked Questions

Typically 24 hours globally, though often faster.

Yes, for most small-to-medium sites needing basic caching and DDoS protection.

USD 20/month, approximately NPR 2,650 at current exchange rates.

Set Cloudflare SSL mode to Full (Strict) and ensure your origin server has a valid certificate installed. In Laravel, set APP_URL to https and trust proxy headers via TrustProxies middleware so the application correctly detects secure requests. Using Flexible mode causes infinite redirects because Laravel generates http links while Cloudflare forces https. I have debugged this exact loop on multiple production Laravel deployments where developers initially chose Flexible mode for convenience. Always validate certificate chains at the origin before switching modes.

This usually happens when Cloudflare caches an error response or your origin blocks Cloudflare IP ranges. Check that your firewall allows Cloudflare IPs listed in their documentation. Verify cache rules do not store 404 responses by setting edge TTL to bypass for error status codes. On WooCommerce sites I maintain, this occurred when security plugins blocked Cloudflare proxies. Purge the specific URL cache first rather than everything. Confirm asset paths are absolute or protocol-relative, as mixed content triggers failures under Cloudflare’s automatic HTTPS rewrites.

Use Standard caching for most Laravel and WordPress sites. This respects query strings and cookies appropriately without aggressive caching that breaks sessions. Avoid Aggressive mode unless you have verified static-only pages, as it strips query parameters needed for pagination and filters. On legal-tech portals handling form submissions and user authentication, Standard prevents cached private data leakage. Configure Page Rules to bypass cache entirely for admin panels, checkout flows, and API endpoints. Test thoroughly in staging before applying globally to production environments serving authenticated users.

Create Page Rules matching dashboard URL patterns with Cache Level set to Bypass. For Laravel apps using Spatie Permission or similar RBAC packages, also add Cookie-based cache exclusion for session tokens. On client portals like Mijar Law Associates, I configure bypass rules for all authenticated routes before enabling any site-wide caching. Never rely solely on no-cache headers from PHP; Cloudflare may still serve stale content if misconfigured. Verify exclusions using curl with cf-cache-status header inspection. Document these rules in deployment checklists since they are easily overlooked during migrations.

Enable Auto Minify for HTML/CSS/JS, activate Brotli compression, and use Rocket Loader cautiously as it can break jQuery-dependent themes. Polish images with lossless or lossy compression depending on visual tolerance. On WooCommerce stores like Petals Nepal, combining these reduced LCP by 1-2 seconds without code changes. Disable email obfuscation if it injects blocking scripts. Prefer serving WebP via Cloudflare Images only if origin lacks conversion capability. Measure improvements with field data from CrUX rather than synthetic lab tests, as real-user metrics determine actual SEO impact.

Whitelist payment gateway IP ranges in Cloudflare WAF and disable challenge pages for webhook endpoints. Payment callbacks fail silently when Cloudflare presents CAPTCHA or JS challenges to automated systems. On Nepal Gift Card platform, we created dedicated Page Rules bypassing security checks for /webhook/esewa and /webhook/khalti paths. Validate webhook signatures server-side regardless of network-layer protections. Monitor failed deliveries in gateway dashboards, not just application logs. Test with sandbox credentials after every Cloudflare rule change, as updates can inadvertently block legitimate callback traffic critical for order confirmation workflows.

No. Cloudflare protects the edge but your origin remains vulnerable to direct IP access, outdated software, and misconfigurations. Continue maintaining UFW firewalls, fail2ban, regular PHP updates, and secure file permissions on Ubuntu servers. On production deployments I manage, Cloudflare stops volumetric attacks while server-level controls handle application logic abuse and local privilege escalation. Expose origin only to Cloudflare IPs via firewall rules. Treat Cloudflare as one layer in defense-in-depth strategy, not a complete solution. Neglecting origin security creates false confidence that leads to breaches despite active CDN protection.

High TTFB indicates slow origin processing, not CDN failure. Check cf-cache-status header: MISS means Cloudflare forwarded request to origin. Profile PHP execution with Laravel Debugbar or Xdebug to identify database queries or external API calls causing delays. On booking systems like Adventure Third Pole Trek, uncached itinerary searches caused 3+ second TTFB until we added Redis caching. Enable Cloudflare Argo Smart Routing only after optimizing origin performance. Cached responses should return sub-100ms TTFB; consistent misses signal architectural issues requiring application-level fixes rather than CDN tuning.

Yes, but understand precedence. Cloudflare processes requests before they reach Apache, so its Page Rules and WAF rules execute first. Origin .htaccess directives still apply to proxied traffic. Conflicts arise when both layers attempt redirects or header modifications. On legacy PHP sites migrated to Cloudflare, I audit rewrite rules to remove redundant HTTPS enforcement already handled at the edge. Test redirect chains with curl -IL to detect double redirects adding latency. Document which layer owns each transformation to simplify future debugging. Keep origin rules minimal when Cloudflare handles equivalent functionality more efficiently.

Import existing zone file first, verify all A, CNAME, MX, and TXT records match current configuration exactly. Lower TTL values to 300 seconds 48 hours before nameserver change. Switch nameservers during low-traffic periods and monitor resolution with dig commands across multiple geographic locations. Keep old DNS provider active for 72 hours post-migration as fallback. On sister sites sharing Deployer 7 pipelines, we stage migrations individually rather than bulk-switching to isolate issues. Never delete original records until new nameservers fully propagate. Validate email delivery separately since MX record errors surface days later.

Caching cart, checkout, or account pages exposes customer data and breaks transactions. Not whitelisting payment gateway IPs causes silent webhook failures. Using Flexible SSL creates security gaps and redirect loops. Enabling Rocket Loader without testing breaks JavaScript-dependent checkout flows. On WooCommerce implementations like Sagun Blossom Flower, these errors caused abandoned carts and failed payments until properly configured. Always exclude dynamic routes via Page Rules before enabling global caching. Test complete purchase flow in staging with real payment sandboxes. Review Cloudflare analytics weekly for unexpected cache hits on sensitive endpoints. Assume default settings are unsafe for transactional sites.

Cloudflare offers superior PoP coverage in South Asia compared to many hosting-bundled CDNs, reducing latency for Nepali users. Free tier includes features others charge for, making it cost-effective for budget-sensitive projects. However, some local ISPs peer better with specific regional CDNs, so test actual performance from Kathmandu and Pokhara using tools like WebPageTest. On legal-tech portals serving primarily domestic traffic, Cloudflare consistently outperformed generic hosting CDNs in TTFB and reliability. Consider hybrid approaches where Cloudflare handles security and global traffic while regional CDN optimizes local delivery. Base decisions on measured performance, not marketing claims or price alone.

Share this article

Quick Contact Options
Choose how you want to connect me: