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: September 2026

A correct Cloudflare CDN setup turns a slow VPS into a fast global site. A sloppy one breaks logins, caches private data, or traps users in redirect loops. I have configured Cloudflare on production Laravel, WordPress, and custom PHP apps for clients in Nepal and abroad. Bandwidth is expensive here. Latency to overseas origins hurts conversion. This guide walks through the exact SSL, DNS, cache, and security settings that survive real traffic—not demo configs that fail on day one.

Before you proxy traffic, confirm your app understands reverse proxies. Laravel must trust forwarded headers. WordPress may need real IP plugins. My guide on Laravel API best practices covers backend trust configuration behind a CDN. Without it, rate limiting, geolocation, and audit logs see Cloudflare IPs—not your visitors.

How do you configure Cloudflare CDN setup and best practices for SSL and DNS?

Most Cloudflare migration outages I diagnose trace back to SSL mode or DNS proxy mistakes. Fix those first. Everything else builds on a clean foundation.

Selecting the correct SSL/TLS encryption mode

Cloudflare offers four encryption modes between the browser and your origin. Only one belongs on production in 2026.

  • Off: Never use in production. Traffic between Cloudflare and origin travels in plain text.
  • Flexible: Avoid. Cloudflare speaks HTTPS to users but HTTP to origin. Laravel, WordPress, and most frameworks force HTTPS and loop forever.
  • Full: Encrypts end-to-end but skips certificate validation. Acceptable only with self-signed origin certs during temporary migration.
  • Full (Strict): The production default. Requires a valid origin certificate matching your hostname. Use Let's Encrypt or a free Cloudflare Origin CA certificate.

On every Laravel and WordPress project I manage, I set Full (Strict) immediately after adding the zone. Pair it with a valid origin cert from Let's Encrypt and Certbot setup. That combination stops redirect loops and closes the gap between edge and origin.

DNS record configuration and proxy status

The orange cloud means proxied. The grey cloud means DNS only. Only HTTP and HTTPS belong behind the orange cloud.

FTP, SSH, SMTP, and database ports must stay grey. Cloudflare's proxy drops non-HTTP traffic. Mail delivery fails silently when MX or mail A records get proxied by mistake.

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

Nepali businesses on shared VPS or local hosting gain two wins from proxying the main domain. DDoS absorption happens at the edge. Your origin IP stays hidden. When evaluating providers alongside CDN work, read cloud hosting services in Nepal and pricing to see which stacks integrate cleanly with Cloudflare. Our domain registration and hosting service often pairs Cloudflare with origin hardening from day one.

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

What cache rules prevent stale content in dynamic applications?

Caching is where Cloudflare setups fail for dynamic apps. Static assets cache fine. HTML with session cookies does not. One wrong rule serves guest pages to logged-in users or leaks CSRF tokens across sessions.

Configuring Cache Rules for Laravel and PHP applications

Cloudflare Cache Rules replaced legacy Page Rules for new zones in 2026. Build rules in priority order. Higher rules win.

  1. Bypass cache for authenticated users: Match cookies like laravel_session, XSRF-TOKEN, or wordpress_logged_in_*. Set cache level to Bypass.
  2. Bypass admin and API routes: Match URI paths /admin/*, /api/*, /dashboard/*, /wp-admin/*. Set cache level to Bypass.
  3. Cache static assets aggressively: Match extensions .css, .js, .png, .jpg, .webp, .woff2, .svg. Set edge TTL to one month.
  4. Cache public HTML cautiously: For marketing pages and blog posts on legal portals I maintain, set TTL to one hour. Enable Respect Origin Headers.
# Cache Rule 1: Bypass authenticated sessions
(http.cookie contains "laravel_session") or
(http.cookie contains "wordpress_logged_in") or
(http.cookie contains "XSRF-TOKEN")
# Action: Cache Level = Bypass

# Cache 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

Test with two browser profiles before go-live. One logged in. One guest. Submit a form on each. Cached HTML with stale CSRF tokens is a common production bug I see on client projects.

Understanding Cache-Control header interactions

Cloudflare respects Cache-Control: private, no-store, and no-cache by default. Laravel sends no-cache, private on web routes by default. Edge rules cannot override that for HTML unless origin headers change.

// Laravel: opt-in caching for public blog post
return response($view)
    ->header('Cache-Control', 'public, max-age=3600')
    ->header('Vary', 'Accept-Encoding');

WordPress sites often use WP Rocket or Cloudflare's official plugin for header management. Custom Laravel builds need explicit middleware. On legal-tech portals with document uploads, I default every sensitive route to private, no-cache. Public pages opt in individually. See caching strategies for web performance for the broader picture beyond Cloudflare alone.

Content TypeRecommended Edge TTLBrowser TTLPurge Strategy
Static assets (CSS/JS/images)1 month1 monthVersioned filenames or purge on deploy
Public HTML (blog, landing pages)1 hour – 24 hours10 minutesPurge via API or plugin on publish
Authenticated/user-specific pagesBypassBypassNot applicable
API JSON responsesBypass or 1 minute0 secondsEvent-driven invalidation
Admin/dashboard routesBypassBypassNot applicable

After deploy, purge cached assets or use fingerprinted filenames from Vite 8.x builds. On a WooCommerce florist project like Petals Qatar flowers shop, product image cache invalidation must follow catalog updates. Otherwise shoppers see old prices.

Cache Rule EvaluationRequest ArrivesCookie + URI checkSession Cookie?laravel_session etc.Admin / API Path?/admin /api /wp-adminBypass CacheDynamic HTMLStatic Extension?css js webp woff2Edge Cache HitTTL up to 1 monthYes → BypassYes → BypassYes → Cache
Cloudflare CDN setup cache decision tree: session cookies and admin paths bypass; static assets cache at the edge

How do you secure applications with Cloudflare WAF and bot management?

Performance gets attention. Security pays for itself faster on Nepali sites facing credential stuffing and scraper traffic. WAF rules block attacks before they hit your PHP-FPM pool.

Enabling and tuning Managed WAF rulesets

Enable Cloudflare Managed Rulesets on every production zone. Start in Log mode for two weeks. Review false positives. Then switch matched rules to Block or Challenge.

Common false positives on my client deployments include:

  • Payment gateway callbacks from eSewa, Khalti, and ConnectIPS flagged as suspicious POST bodies
  • Legal document upload endpoints triggering multipart inspection rules
  • Third-party webhook receivers blocked by rate-limiting rules

Create WAF exceptions for known callback IP ranges. Do not disable OWASP rules globally. One exception on /payment/callback beats turning off SQL injection protection site-wide. Read fail2ban versus Cloudflare for DDoS protection to understand how edge and server layers complement each other.

Bot Fight Mode and rate limiting

Enable Bot Fight Mode on the free tier. It challenges low JavaScript-score requests. Scrapers and credential stuffers drop before reaching origin. For eCommerce checkout flows, Super Bot Fight Mode on Pro plans distinguishes verified bots from hostile automation.

On legal service portals I maintain, bot challenges cut spam form submissions noticeably. Watch the Managed Challenge pass rate in analytics. If more than two percent of legitimate users fail, widen your exception list.

Pair Cloudflare rate limiting with application-level throttling in Laravel. Edge limits protect origin CPU. App limits protect business logic. See how to secure your website and server in Nepal for the full stack beyond CDN settings alone.

Incoming RequestIP + HeadersBot Score CheckJS ChallengeWAF RulesOWASP + CustomRate LimitingPer-IP LimitsCache LookupHit or BypassOrigin ServerPHP-FPM PoolBlock / Challenge403 Response
Cloudflare WAF pipeline: bot detection, managed rules, rate limiting, then cache before origin

Which performance optimizations deliver measurable speed improvements?

Cloudflare caching helps TTFB. Compression and protocol tuning help LCP. Both feed directly into Core Web Vitals optimization and search rankings.

Compression and protocol optimization

Enable Brotli compression under Speed → Optimization. Brotli beats gzip by 15–25% on text assets. Keep gzip as fallback for older clients.

Enable HTTP/3 (QUIC) and Early Hints (103). QUIC cuts connection setup time on mobile networks in Nepal where packet loss is common. Early Hints send preload Link headers while PHP still renders the page.

Image optimization and Polish

Product-heavy sites benefit from Cloudflare Polish on Pro plans. It converts JPEG and PNG to WebP or AVIF at the edge. Pair it with responsive <picture> tags in Blade or WordPress themes.

On budget builds, optimize images at build time with Vite 8.x or Sharp in Laravel. Let Cloudflare cache the pre-compressed output. You keep most of the gain without a Pro subscription. Our speed optimization service often combines origin image pipelines with edge caching for eCommerce clients.

Argo Smart Routing for international audiences

Nepali businesses serving diaspora customers in Australia, the US, or the Gulf benefit from Argo Smart Routing. Traffic rides Cloudflare's private backbone instead of congested public peering. Cost runs roughly $5/month plus per-GB usage—often Rs 700/month base, ~USD 5.

On international eCommerce like Nepal Gift Card, cross-border latency directly affects checkout completion. Argo is worth testing when analytics show high overseas bounce on slow LCP.

User DeviceHTTP/3 QUICBrotli DecodeWebP RenderCloudflare EdgeBrotli CompressHTTP/3 + 103Polish WebPArgo RoutingOrigin ServerRaw HTML/CSSJPEG/PNG Files
Cloudflare CDN setup performance layers: Brotli, HTTP/3, Polish, and Argo between origin and user

How do you troubleshoot common Cloudflare integration failures?

Even correct configs break under edge cases. These four problems account for most tickets I handle after a Cloudflare go-live.

Infinite redirect loops after enabling Cloudflare

SSL mode mismatch causes nearly every redirect loop. Laravel forces HTTPS via middleware. Cloudflare in Flexible mode connects to origin over HTTP. The app redirects to HTTPS. Cloudflare connects over HTTP again. The loop never ends.

Fix: Set SSL to Full (Strict). Install a valid origin certificate. Configure TrustProxies in Laravel:

// app/Http/Middleware/TrustProxies.php
protected $proxies = '*';
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;

WordPress users should follow WordPress Cloudflare integration for speed. The same SSL and cookie rules apply.

Stale content served to authenticated users

Logged-in users seeing guest pages means cache bypass rules miss their cookies. Cloudflare string matching is case-sensitive. Verify exact cookie names in DevTools.

Disable any legacy "Cache Everything" Page Rule during testing. That rule ignores cookies unless you add explicit bypass conditions. Official Cloudflare cache documentation explains how edge TTL interacts with origin headers.

Origin server IP exposure despite proxying

Attackers who find your real IP bypass Cloudflare entirely. Lock ports 80 and 443 to Cloudflare published IP ranges only. Reject all other inbound HTTP traffic with UFW. See UFW firewall rules for web servers for the exact allowlist commands.

Real client IP not reaching the application

Cloudflare sends the visitor IP in CF-Connecting-IP and X-Forwarded-For. Your web server must pass those headers to PHP-FPM. On Nginx, add the real IP module config documented in Laravel deployment on Ubuntu with Nginx. Apache needs RemoteIP module configuration.

Validate header parsing with a quick JSON payload test in our JSON formatter tool after logging a test request. Confirm the IP field matches your actual address—not a Cloudflare range.

For broader context on why CDN investment matters locally, read why every Nepali business should use CDN for speed. Align technical choices with market realities before you cut over DNS.

Key Takeaways

  • Set SSL to Full (Strict) with a valid origin certificate before proxying any production traffic.
  • Build Cache Rules that bypass sessions, admin paths, and API routes—then cache static assets for one month.
  • Enable WAF managed rules in Log mode first; whitelist payment callbacks and webhooks before blocking.
  • Turn on Brotli, HTTP/3, and Early Hints; optimize images at origin if Pro Polish is not in budget.
  • Restrict origin ports 80/443 to Cloudflare IP ranges so attackers cannot bypass the edge.
  • Purge cache or version assets on every deploy; test with logged-in and guest browser profiles.

People Also Ask

Is Cloudflare CDN free enough for a small business website?

Yes. The free plan includes CDN caching, Universal SSL, basic DDoS protection, and Bot Fight Mode. That covers most brochure sites and small WordPress shops. Upgrade when you need Polish image optimization, advanced WAF tuning, or SLA-backed support.

How long does Cloudflare CDN setup take?

DNS propagation takes up to 48 hours globally. Actual configuration—SSL, cache rules, WAF—takes one to three hours for a standard Laravel or WordPress site. Complex multi-domain setups with staging environments need a full day including testing.

Does Cloudflare work with shared hosting in Nepal?

Yes, as long as your host allows custom DNS and origin HTTPS. Point nameservers or individual A records to Cloudflare. Set SSL to Full (Strict). Some budget hosts block outbound ports or use shared IPs—verify compatibility before migrating production traffic.

Should I use Cloudflare or AWS CloudFront for a Laravel app?

Cloudflare suits most Laravel VPS deployments: simpler DNS, built-in WAF, and no S3 requirement. CloudFront pairs better with S3-hosted assets on AWS-native stacks. Compare approaches in AWS CloudFront CDN setup for Laravel assets if your infrastructure is already on AWS.

Ship Cloudflare CDN Setup That Survives Production Traffic

Effective Cloudflare CDN setup rests on three habits. Encrypt with Full (Strict). Cache selectively by authentication state and content type. Layer security from bot challenges through WAF to origin firewall rules. Treat Cloudflare as application architecture—not a checkbox after launch.

Test every change in staging first. Monitor analytics for WAF false positives. Document cache rules alongside your codebase. If you want an audit of an existing zone—or hands-on setup for Laravel, WordPress, or custom PHP—contact us for a production review. I also take direct enquiries via my contact page. For ongoing tuning, our SEO service and page speed optimization checklist cover the metrics side after CDN work is done.

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

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: