When architecting high-throughput web applications and mission-critical content platforms, combining a global Anycast Content Delivery Network (CDN) with an enterprise origin web server represents the benchmark of modern web scalability. However, naive deployments that pair Cloudflare’s edge proxy with LiteSpeed Web Server (LSWS) and the LiteSpeed Cache (LSCache) engine frequently stumble into crippling operational pitfalls—including double-caching pathologies, desynchronized edge purges, corrupted session headers, and broken client IP logging. At MeraHost, deploying thousands of high-concurrency environments on enterprise NVMe infrastructure has demonstrated that achieving sub-50ms global TTFB requires treating Cloudflare and LiteSpeed not as competing cache layers, but as a unified, symbiotically tuned edge-to-core acceleration pipeline.
How to Use Cloudflare with LiteSpeed Cache: The Enterprise Blueprint
LiteSpeed Web Server is engineered from the ground up to outperform traditional Apache and Nginx web servers in dynamic PHP execution, particularly for platforms like WordPress, Magento, and Drupal. LiteSpeed achieves this through native server-level caching (LSCache), communicating directly through shared memory (SHM) segments rather than through external reverse proxy bottlenecks. Meanwhile, Cloudflare operates an Anycast edge spanning over 330 cities across more than 120 countries, terminating TLS handshakes physically close to end-users and buffering static binaries.
When these two powerhouses are misconfigured, severe performance degradation and stale content anomalies arise. If both Cloudflare and LiteSpeed attempt to cache dynamic HTML without an active synchronization channel, an updated e-commerce price or newly published editorial will refresh on the origin server within seconds—yet continue serving stale HTML from Cloudflare’s edge data centers for hours. Conversely, aggressive edge caching rules that ignore LiteSpeed’s Vary headers can leak authenticated administrative session bars or private WooCommerce shopping cart states to unauthorized visitors. This guide delivers the architectural roadmap to eliminate these conflicts, configure automated edge purge webhooks, harden TCP/IP networking, and optimize throughput across the entire delivery chain.
Architectural Topology: Unifying the Edge Proxy and Origin Cache
To design an optimal Cloudflare LiteSpeed pipeline, we must map the anatomy of an HTTP request as it traverses from the client browser, through the edge Anycast network, across the WAN backbone, and into the LiteSpeed origin kernel. The lifecycle operates through four distinct layers:
- Edge Ingress & TLS Termination: The client resolves DNS to Cloudflare Anycast IP addresses. Cloudflare terminates TLS 1.3 or HTTP/3, applies Layer 3/4 and Layer 7 Web Application Firewall (WAF) filtering, and checks its local edge cache for static assets (images, CSS, JS, fonts).
- Origin Forwarding & True IP Preservation: For cache misses or dynamic requests, Cloudflare proxies the request back to the LiteSpeed origin server over an encrypted backhaul tunnel (enforcing TLS 1.3 with Cloudflare Origin CA). Cloudflare attaches the client’s actual IP address in the
CF-Connecting-IPandX-Forwarded-ForHTTP request headers. - Origin Shared-Memory Processing: LiteSpeed Web Server intercepts the ingress request. If the URI is eligible for caching, LiteSpeed queries its Shared Memory (SHM) hash table. On an origin cache HIT, LiteSpeed streams the pre-compressed (gzip/Brotli) static HTML directly from NVMe storage into the TCP socket, completely bypassing the PHP runtime engine and database.
- Asynchronous Tag-Based Purge Synchronization: When content changes (e.g., a post edit, taxonomy change, or stock update), LiteSpeed Cache immediately invalidates the associated cache tags locally. Simultaneously, via background curl workers, LSCache calls Cloudflare’s REST API (
/client/v4/zones/{zone_id}/purge_cache) to purge either the specific URLs or the entire edge cache zone, guaranteeing immediate global synchronization.
| Architecture Metric | Naive / Misconfigured Stack | Enterprise Tuned Cloudflare + LiteSpeed |
|---|---|---|
| Global Static Asset TTFB | 180ms – 450ms (Origin misses) | 12ms – 35ms (Cloudflare Edge Cache Hit) |
| Origin Dynamic HTML TTFB | 380ms – 1100ms (PHP/MySQL query loop) | 18ms – 45ms (LiteSpeed SHM Hit on NVMe) |
| Cache Purge Synchronization | Manual purge or stale 4-hour edge TTL | Instant Automated Edge Purge via Scoped API |
| Client IP Logging & Security | Cloudflare reverse-proxy IPs logged (Broken WAF) | True Visitor IP Restored via UseClientIPInHeader |
| SSL/TLS Cryptographic Security | Flexible SSL (Vulnerable to MITM & Redirect Loops) | Full (Strict) TLS 1.3 with Cloudflare Origin CA |
| Origin Concurrency Ceiling | ~250 concurrent unbuffered requests | 25,000+ concurrent requests (98% Edge/SHM Offload) |
| Dynamic State Isolation | Leaked shopping carts via naive Edge Caching | Strict Cookie/Vary Isolation via LSCache Tags |
Architecture Note: Avoid Cloudflare’s blanket “Cache Everything” Page Rule unless you are running Cloudflare Automatic Platform Optimization (APO) or custom edge Cloudflare Workers. Without proper worker logic, “Cache Everything” will indiscriminately cache dynamic HTML responses containing user session cookies, displaying logged-in customer dashboards, WooCommerce cart fragments, or WordPress administrative controls to other visitors.
Step 1: Restoring Real Visitor IPs in LiteSpeed Web Server
Because Cloudflare operates as a reverse proxy, every incoming connection hitting your LiteSpeed origin server originates from Cloudflare’s Anycast IP addresses. If your origin web server is not configured to extract the real visitor IP from the CF-Connecting-IP request header, three catastrophic problems occur:
- Security Failures: Origin firewalls (such as ConfigServer Security & Firewall – CSF, Fail2ban, or LiteSpeed Per-Client Throttling) will mistakenly ban Cloudflare’s edge proxy IPs rather than the offending attacker, taking your entire website offline for everyone routed through that edge PoP.
- Broken Analytics & Geo-Targeting: WordPress comment logging, WooCommerce fraud scoring, and geo-currency selectors will read Cloudflare’s data center locations instead of the end-user’s geographic origin.
- Vary Header Desynchronization: LiteSpeed Cache’s geo-caching and mobile-view caching engines will fail to identify visitor variations accurately.
To resolve this natively inside LiteSpeed Web Server, configure the useIpInProxyHeader directive within your LiteSpeed configuration console or directly in /usr/local/lsws/conf/httpd_config.conf. When set to 2 (or Trusted IP Only), LiteSpeed inspects the proxy header only if the connecting socket originates from a trusted upstream IP address.
LiteSpeed Web Server Origin IP Configuration (/usr/local/lsws/conf/httpd_config.conf):
# Enable Client IP extraction from Cloudflare proxy headers
useIpInProxyHeader 2
# Trust all official Cloudflare IPv4 and IPv6 Anycast ranges
# Ensure accessControl allow list permits Cloudflare edge subnets
accessControl {
allow ALL, 173.245.48.0/20T, 103.21.244.0/22T, 103.22.200.0/22T, 103.31.4.0/22T, 141.101.64.0/18T, 108.162.192.0/18T, 190.93.240.0/20T, 188.114.96.0/20T, 197.234.240.0/22T, 198.41.128.0/17T, 162.158.0.0/15T, 104.16.0.0/13T, 104.24.0.0/14T, 172.64.0.0/13T, 131.0.72.0/22T, 2400:cb00::/32T, 2606:4700::/32T, 2803:f800::/32T, 2405:b500::/32T, 2405:8100::/32T, 2a06:98c0::/29T, 2c0f:f248::/32T
}
If you are operating OpenLiteSpeed (OLS) or utilizing an Apache-compatible configuration file with mod_remoteip, apply the equivalent directive inside your virtual host container or Apache include configuration:
Apache / OpenLiteSpeed RemoteIP Configuration (/etc/apache2/conf-available/remoteip.conf):
# Define the real IP header injected by Cloudflare
RemoteIPHeader CF-Connecting-IP
# Trusted Cloudflare IPv4 CIDR blocks
RemoteIPTrustedProxy 173.245.48.0/20
RemoteIPTrustedProxy 103.21.244.0/22
RemoteIPTrustedProxy 103.22.200.0/22
RemoteIPTrustedProxy 103.31.4.0/22
RemoteIPTrustedProxy 141.101.64.0/18
RemoteIPTrustedProxy 108.162.192.0/18
RemoteIPTrustedProxy 190.93.240.0/20
RemoteIPTrustedProxy 188.114.96.0/20
RemoteIPTrustedProxy 197.234.240.0/22
RemoteIPTrustedProxy 198.41.128.0/17
RemoteIPTrustedProxy 162.158.0.0/15
RemoteIPTrustedProxy 104.16.0.0/13
RemoteIPTrustedProxy 104.24.0.0/14
RemoteIPTrustedProxy 172.64.0.0/13
RemoteIPTrustedProxy 131.0.72.0/22
# Trusted Cloudflare IPv6 CIDR blocks
RemoteIPTrustedProxy 2400:cb00::/32
RemoteIPTrustedProxy 2606:4700::/32
RemoteIPTrustedProxy 2803:f800::/32
RemoteIPTrustedProxy 2405:b500::/32
RemoteIPTrustedProxy 2405:8100::/32
RemoteIPTrustedProxy 2a06:98c0::/29
RemoteIPTrustedProxy 2c0f:f248::/32
Step 2: Automating Cloudflare Edge Purging in LiteSpeed Cache
The most critical integration point between LiteSpeed and Cloudflare is automated edge cache invalidation. LiteSpeed Cache features native Cloudflare API hooks. When an author publishes a new article, edits a WooCommerce product inventory count, or deletes a spam comment, LiteSpeed invalidates its local origin shared-memory cache immediately. By supplying your Cloudflare API credentials into the LiteSpeed Cache settings, LSCache sends an instant REST call to Cloudflare to purge the edge simultaneously.
- Generate a Scoped Cloudflare API Token: Log into the Cloudflare Dashboard, navigate to My Profile > API Tokens, and click Create Token. Do NOT use your global API key. Select the Custom Token template and grant the following permissions:
Zone > Cache Purge > PurgeZone > Zone > Read
Restrict the Zone Resources to your specific domain to adhere to the principle of least privilege.
- Locate Zone ID: In the Cloudflare overview tab for your domain, scroll down to the bottom right sidebar under the API heading to copy your 32-character Zone ID.
- Configure LiteSpeed Cache Plugin: Inside your WordPress admin dashboard, navigate to LiteSpeed Cache > CDN > Cloudflare Settings:
- Cloudflare API: Set toggle to
ON. - API Token / Global Key: Enter your Scoped Cloudflare API Token.
- Email: Enter your Cloudflare account email address (if using API Token, this can be omitted depending on plugin version).
- Domain: Enter your apex domain (e.g.,
example.com). - Zone ID: Paste the 32-character Zone ID copied from Cloudflare.
- Cloudflare API: Set toggle to
- Enable Auto-Purge Hooks: Under LiteSpeed Cache > Purge, ensure that automatic purge hooks are active for Front Page, Home Page, Pages, All Categories, and Post Tags upon publishing.
Architecture Note: When managing high-traffic editorial portals, avoid triggering a full “Purge All” on every minor post update. Full zone purges flush all static assets globally, forcing millions of subsequent requests back to your origin server simultaneously (a thundering herd condition). LiteSpeed Cache’s granular URL and tag-based purges selectively clear only modified resources, keeping your origin CPU load near zero.
Step 3: Linux Kernel & TCP Socket Tuning for Ingress Edge Traffic
When thousands of Cloudflare edge nodes establish concurrent TCP connections to your LiteSpeed origin server, default Linux kernel network parameters quickly become saturated. In a default Linux deployment, connection backlogs are limited to 128 or 1024 slots, causing socket drops, SYN flood false alarms, and high connection latency. To guarantee flawless edge-to-origin data transit, deploy this hardened sysctl profile to /etc/sysctl.d/99-cloudflare-litespeed.conf.
Production Linux Kernel Network Optimization (/etc/sysctl.d/99-cloudflare-litespeed.conf):
# Enable Google BBR Congestion Control for high-throughput edge backhaul
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
# Increase socket listen backlog to absorb Cloudflare burst connections
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 16384
# Expand ephemeral port range for massive outbound API purges and proxies
net.ipv4.ip_local_port_range = 10240 65535
# Enable TCP SYN Cookies for Layer 4 SYN flood resilience
net.ipv4.tcp_syncookies = 1
# Optimize TCP socket reuse and teardown latency
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
# Enable TCP Fast Open (TFO) for client-to-server and proxy-to-origin handshakes
# 3 enables both incoming and outgoing TFO
net.ipv4.tcp_fastopen = 3
# Buffer tuning: Allocate sufficient memory for high-bandwidth WAN connections
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
# Disable slow start after idle to maintain high transfer rates across keep-alive connections
net.ipv4.tcp_slow_start_after_idle = 0
# Maximum number of orphaned (closed) TCP connections allowed
net.ipv4.tcp_max_orphans = 262144
After creating the file, apply the network modifications immediately without rebooting the server using the sysctl command:
sysctl --system
Step 4: Automated Synchronization of Cloudflare IP Subnets
Cloudflare occasionally modifies, expands, or reclaims IP prefixes from its Anycast routing pool. Hardcoding static IP lists into your firewall or web server configuration introduces maintenance risk. If Cloudflare routes traffic through a newly announced subnet that is missing from your trusted list, visitors routed through that PoP will either be blocked by your firewall or have their real IPs logged as Cloudflare proxy IPs.
Deploy this automated Bash maintenance script and systemd timer to pull official Cloudflare IP ranges from their published endpoints, rebuild an ipset allowlist, update LiteSpeed’s trusted IP configuration, and gracefully reload the web server without dropping a single active transaction.
Production IP Sync Script (/usr/local/bin/sync-cloudflare-ips.sh):
#!/usr/bin/env bash
# ==============================================================================
# Enterprise Cloudflare IP Synchronizer for LiteSpeed Web Server
# Fetches dynamic Anycast subnets and synchronizes iptables / ipset & LiteSpeed
# ==============================================================================
set -euo pipefail
CLOUDFLARE_V4_URL="https://www.cloudflare.com/ips-v4"
CLOUDFLARE_V6_URL="https://www.cloudflare.com/ips-v6"
TARGET_CONF="/usr/local/lsws/conf/cloudflare_ips.conf"
TMP_DIR=$(mktemp -d /tmp/cf_sync.XXXXXX)
cleanup() {
rm -rf "${TMP_DIR}"
}
trap cleanup EXIT
echo "[+] Fetching current Cloudflare IPv4 and IPv6 subnets..."
curl -fsSL --retry 3 --connect-timeout 10 "${CLOUDFLARE_V4_URL}" -o "${TMP_DIR}/ips-v4"
curl -fsSL --retry 3 --connect-timeout 10 "${CLOUDFLARE_V6_URL}" -o "${TMP_DIR}/ips-v6"
# Verify fetched payloads contain valid IP ranges
if [[ ! -s "${TMP_DIR}/ips-v4" ]] || [[ ! -s "${TMP_DIR}/ips-v6" ]]; then
echo "[-] ERROR: Empty payload received from Cloudflare API. Aborting."
exit 1
fi
echo "[+] Generating LiteSpeed accessControl trusted subnet directive..."
printf 'accessControl {\n allow ALL, ' > "${TMP_DIR}/cloudflare_ips.conf"
sed 's/$/T, /' "${TMP_DIR}/ips-v4" | tr -d '\n' >> "${TMP_DIR}/cloudflare_ips.conf"
sed 's/$/T, /' "${TMP_DIR}/ips-v6" | tr -d '\n' | sed 's/, $//' >> "${TMP_DIR}/cloudflare_ips.conf"
printf '\n}\n' >> "${TMP_DIR}/cloudflare_ips.conf"
# Atomically replace production configuration if content differs
if ! cmp -s "${TMP_DIR}/cloudflare_ips.conf" "${TARGET_CONF}" 2>/dev/null; then
mv "${TMP_DIR}/cloudflare_ips.conf" "${TARGET_CONF}"
chmod 644 "${TARGET_CONF}"
echo "[+] Configuration updated. Performing graceful LiteSpeed reload..."
systemctl reload lsws || /usr/local/lsws/bin/lswsctrl restart
else
echo "[*] Cloudflare subnets unchanged. No reload required."
fi
# Synchronize IPSet for kernel-level firewall bypass
if command -v ipset >/dev/null 2>&1; then
echo "[+] Synchronizing kernel IPSet 'cloudflare-v4'..."
ipset create cloudflare-v4 hash:net family inet -exist
ipset create cf-temp-v4 hash:net family inet -exist
while read -r cidr; do
[[ -n "${cidr}" ]] && ipset add cf-temp-v4 "${cidr}" -exist
done < "${TMP_DIR}/ips-v4"
ipset swap cf-temp-v4 cloudflare-v4
ipset destroy cf-temp-v4
fi
echo "[✓] Cloudflare IP synchronization completed successfully."
Systemd Service Unit (/etc/systemd/system/cloudflare-ip-sync.service):
[Unit]
Description=Automated Cloudflare IP Synchronizer for LiteSpeed
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/sync-cloudflare-ips.sh
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Systemd Timer Unit (/etc/systemd/system/cloudflare-ip-sync.timer):
[Unit]
Description=Weekly Cloudflare Subnet Sync Timer
[Timer]
OnCalendar=Sun *-*-* 03:00:00
RandomizedDelaySec=1800
Persistent=true
[Install]
WantedBy=timers.target
Enable and start the systemd timer using standard systemctl commands:
chmod +x /usr/local/bin/sync-cloudflare-ips.sh
systemctl daemon-reload
systemctl enable --now cloudflare-ip-sync.timer
Step 5: Cloudflare Edge Optimization Rules for LiteSpeed
Within your Cloudflare Dashboard, configure these specific settings to complement LiteSpeed’s native caching behavior rather than interfering with it:
- Caching Level: Set to Standard under Caching > Configuration. This tells Cloudflare to cache all static asset extensions (.css, .js, .webp, .jpg, .svg, .woff2) according to origin headers while letting dynamic HTML requests pass directly through to LiteSpeed.
- Browser Cache TTL: Set to Respect Existing Headers. LiteSpeed Cache outputs optimized
Cache-Controlmax-age headers for both static and dynamic assets. Respecting existing headers ensures Cloudflare does not override LiteSpeed’s intentional cache lifetimes. - Tiered Cache & Argo: Enable Tiered Cache (Smart Tiered Cache Topology). Cloudflare’s regional data centers will elect specialized upper-tier hubs to fetch assets from your origin server once, distributing cached copies to all surrounding lower-tier edge PoPs and drastically slashing origin bandwidth consumption.
- SSL/TLS Encryption Mode: Set strictly to Full (Strict). Install a free 15-year Cloudflare Origin CA certificate inside your LiteSpeed virtual host. Never use Flexible SSL; Flexible SSL transmits unencrypted HTTP between Cloudflare and your origin server, exposing your credentials over public backhaul lines and triggering infinite redirect loops if HTTPS rewrites are enabled.
- Minification Settings: Disable Cloudflare’s Auto-Minify (HTML, CSS, JS) if you have already enabled CSS/JS Minification, Combining, and Critical CSS generation inside the LiteSpeed Cache plugin. Running dual minification engines consumes CPU cycles and often introduces JavaScript parse errors due to redundant variable renaming.
Architecture Note: When conducting speed tests on webpagetest.org or Google PageSpeed Insights, always check the HTTP response headers. A perfectly configured Cloudflare LiteSpeed stack will return
CF-Cache-Status: HITfor static assets, andCF-Cache-Status: DYNAMICalongsideX-LiteSpeed-Cache: hitfor uncached edge HTML requests that hit LiteSpeed’s shared-memory cache.
Production Readiness & Performance Verification Checklist
Before promoting your Cloudflare LiteSpeed stack to live production traffic, verify each layer with this diagnostic curl command executed from an external terminal:
# Test dynamic page caching and header preservation
curl -I -s https://example.com/ | grep -Ei "(cf-cache-status|x-litespeed-cache|content-encoding|alt-svc)"
# Expected Output on second request:
# cf-cache-status: DYNAMIC
# x-litespeed-cache: hit
# content-encoding: br
# alt-svc: h3=":443"; ma=86400
For engineering teams seeking ultra-reliable cloud hosting without having to manually manage low-level kernel configurations, deploying on MeraHost Enterprise Cloud provides an out-of-the-box, fully managed LiteSpeed Web Server environment running on enterprise NVMe storage arrays with native Cloudflare edge compatibility pre-tuned.
Frequently Asked Questions
Does Cloudflare replace the need for LiteSpeed Cache at the origin?
No. Cloudflare excels at edge asset distribution, DDoS mitigation, and edge TLS termination, but by default it does not cache dynamic HTML pages. When a user requests an HTML page, Cloudflare forwards the request to your origin server. LiteSpeed Cache executes at the origin, serving pre-rendered pages directly from shared memory in under 20ms without invoking PHP or MySQL. Without LiteSpeed Cache, every edge cache-miss will force your origin server to execute costly database queries.
Why do I see Cloudflare IP addresses in WordPress comment logs and security alerts?
This occurs because LiteSpeed Web Server is not configured to trust Cloudflare as a reverse proxy. To fix this, enable useIpInProxyHeader 2 in LiteSpeed’s httpd_config.conf or configure RemoteIPHeader CF-Connecting-IP with Cloudflare’s trusted IP ranges. Once configured, LiteSpeed replaces Cloudflare’s proxy IP with the real visitor IP address before passing the request to PHP and WordPress.
Can I use Cloudflare APO (Automatic Platform Optimization) with LiteSpeed Cache?
While technically possible, running Cloudflare APO alongside LiteSpeed Cache is generally redundant and can introduce cache invalidation race conditions. If you choose to use Cloudflare APO, you must ensure that LiteSpeed Cache handles object caching and CSS/JS optimization while delegating page caching to APO. For most enterprise websites, using LiteSpeed Cache for page caching combined with Cloudflare’s Standard edge caching and automated API purges provides superior flexibility, tag-based purging, and granular cache controls.
What happens when I purge the cache in the LiteSpeed Cache WordPress plugin?
When configured with a scoped Cloudflare API token, purging a page or category in LiteSpeed Cache immediately clears the corresponding entry from LiteSpeed’s origin shared memory and simultaneously dispatches an asynchronous API call to Cloudflare. Cloudflare purges that specific URL from its global edge data centers within seconds, ensuring visitors worldwide immediately receive the fresh content without stale caching delays.
Deploy Enterprise-Grade Production Infrastructure
Need guaranteed performance with zero price hikes? Host mission-critical workloads on MeraHost with pure Enterprise NVMe, LiteSpeed Web Server, and Same Renewal Price, Always (starting at ₹99/mo).