โ ๏ธ Important Implementation Notice
Recommendation: Implement Cloudflare only after completing your entire site setup. Cloudflare adds an additional layer of caching which can make troubleshooting more difficult during initial configuration.
Security Requirement: Enable two-factor authentication on your Cloudflare account immediately. Securing your Cloudflare account is critical to protecting your entire web infrastructure.
๐ Table of Contents
- Cloudflare Overview & Benefits
- The IP Address Problem
- Server-Side Configuration
- Dashboard Configuration
- Automatic Platform Optimization
1. Cloudflare Overview & Benefits
Cloudflare is a content delivery network (CDN) and security service that acts as a reverse proxy between your visitors and your server. The free plan provides substantial benefits for WordPress hosting:
๐ Performance
Global CDN distributes content across data centers worldwide, ensuring faster access regardless of user location.
๐ก๏ธ Security
DDoS protection and bot mitigation safeguard against malicious traffic and attacks.
๐ SSL/TLS
Free SSL certificates ensure secure connections for all visitors.
๐ Analytics
Insights into site traffic, threats, and performance metrics.
๐พ Bandwidth Savings
Caching static resources reduces server load and bandwidth consumption.
๐ญ IP Masking
Your server's IP address is hidden behind Cloudflare's network.
2. The IP Address Problem
Understanding the Issue
When Cloudflare is enabled, all traffic is routed through their network. This means your server logs will only show Cloudflare's IP addresses instead of the actual visitor IP addresses. This creates problems for:
- Fail2Ban: Cannot properly identify and block malicious visitors
- Analytics: Cannot track actual visitor locations and patterns
- Access Control: IP-based restrictions won't work correctly
- Web Applications: Logic relying on visitor IPs will malfunction
Traffic Flow Diagram
(Real IP: 203.0.113.45)
(Proxy Layer)
(Sees Cloudflare IP)
Solution: Cloudflare includes the visitor's real IP in
headers: X-Forwarded-For and CF-Connecting-IP
The Solution: HTTP Real IP Module
Ubuntu's NGINX includes the http_realip_module by default. This module allows NGINX to recognize the original visitor IP address from HTTP headers when requests come from trusted sources (Cloudflare's IP ranges).
3. Server-Side Configuration
๐จ Important Warning About Automation
Do NOT use automated scripts to download Cloudflare IP addresses. Here's why:
- Cloudflare sometimes adds CAPTCHA challenges to their IP list pages
- Automated scripts will fail when presented with a CAPTCHA
- Failed downloads can corrupt your NGINX configuration
- If NGINX fails to start after a reboot, your sites will be down
Recommendation: Update the IP list manually. Cloudflare's IP addresses change infrequently.
1Create the Cloudflare IP List File
First, obtain the latest Cloudflare IP addresses from the official sources:
- IPv4: https://www.cloudflare.com/ips-v4
- IPv6: https://www.cloudflare.com/ips-v6
Navigate to the NGINX includes directory and create the configuration file:
2Configure the IP List File
Add the following content to the file. Each Cloudflare IP range must be prefixed with
set_real_ip_from:
# Last updated: Check https://www.cloudflare.com/ips-v4 and /ips-v6 for current list # IPv4 Ranges set_real_ip_from 173.245.48.0/20; set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 108.162.192.0/18; set_real_ip_from 190.93.240.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; set_real_ip_from 162.158.0.0/15; set_real_ip_from 104.16.0.0/13; set_real_ip_from 104.24.0.0/14; set_real_ip_from 172.64.0.0/13; set_real_ip_from 131.0.72.0/22; # IPv6 Ranges set_real_ip_from 2400:cb00::/32; set_real_ip_from 2606:4700::/32; set_real_ip_from 2803:f800::/32; set_real_ip_from 2405:b500::/32; set_real_ip_from 2405:8100::/32; set_real_ip_from 2a06:98c0::/29; set_real_ip_from 2c0f:f248::/32; # Specify which header contains the real IP real_ip_header CF-Connecting-IP;
Understanding the Directives:
- set_real_ip_from: Defines trusted IP ranges (Cloudflare's network)
- real_ip_header: Specifies which HTTP header contains the real visitor IP
- CF-Connecting-IP: Cloudflare's header containing the original visitor IP address
3Verify the File Path
Confirm the complete file path for reference:
Expected output: /etc/nginx/includes/cloudflare_ip_list.conf
4Include File in Server Block
Navigate to your site's configuration directory:
Add the include directive in your server block, preferably after other security includes:
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# Other directives...
include /etc/nginx/includes/nginx_security_directives.conf;
include /etc/nginx/includes/cloudflare_ip_list.conf;
# Rest of configuration...
}
5Test and Apply Configuration
Always test the NGINX configuration before applying changes:
Expected Output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
If the test is successful, reload NGINX to apply the configuration:
6Verify IP Logging
After enabling Cloudflare proxy and completing the configuration, test that your logs show real visitor IPs:
Visit your site and check that the logged IP addresses are visitor IPs, not Cloudflare IPs.
4. Cloudflare Dashboard Configuration
๐งช Test on Development First
Always test new Cloudflare features on a development server before applying them to production. This approach prevents downtime and allows you to understand the impact of configurations.
1DNS Configuration
Log into your Cloudflare account and select your domain. Navigate to DNS settings.
Enable Proxy Status
This is the most critical setting. You must change the proxy status for your domain records:
| Setting | Description | Recommended |
|---|---|---|
| DNS Only | Cloudflare only provides DNS resolution. Traffic goes directly to your server. | โ No |
| Proxied | Traffic routes through Cloudflare's network. Full features enabled. | โ Yes |
Steps to Enable Proxy:
- Find your A record (example.com)
- Click Edit
- Toggle from DNS Only (grey cloud) to Proxied (orange cloud)
- Click Save
- Repeat for your CNAME record (www.example.com)
Important: Do NOT change MX records (mail records) to Proxied status. Email services require DNS Only mode.
2SSL/TLS Configuration
Navigate to SSL/TLS in your Cloudflare dashboard.
Encryption Mode
Set encryption mode to Full (Strict). This is critical for security:
| Mode | Visitor โ Cloudflare | Cloudflare โ Server | Recommendation |
|---|---|---|---|
| Off | Unencrypted | Unencrypted | โ Never use |
| Flexible | Encrypted | Unencrypted | โ Insecure |
| Full | Encrypted | Encrypted (any cert) | โ ๏ธ Not recommended |
| Full (Strict) | Encrypted | Encrypted (valid cert) | โ Use this |
Full (Strict) Explained:
- Visitor โ Cloudflare: Encrypted with Cloudflare's SSL certificate
- Cloudflare โ Your Server: Encrypted with your server's valid SSL certificate (Let's Encrypt)
- End-to-end encryption ensures maximum security
Edge Certificates
Navigate to SSL/TLS โ Edge Certificates:
- Always Use HTTPS: โ Enable (automatically redirects HTTP to HTTPS)
- HTTP Strict Transport Security (HSTS): โ Do NOT enable (already configured on server)
- Minimum TLS Version: Set to TLS 1.2 (never use TLS 1.0 or 1.1)
- TLS 1.3: โ Enable (latest, fastest, most secure)
โ ๏ธ HSTS Warning
Since you've already configured HSTS headers on your NGINX server, do NOT enable HSTS in Cloudflare. Duplicate HSTS headers can cause conflicts.
3Speed Optimization
Navigate to Speed โ Optimization โ Content Optimization:
| Feature | Description | Recommendation |
|---|---|---|
| Cloudflare Fonts | Optimizes font loading from Google Fonts and other providers | โ Enable |
| Early Hints | Sends HTTP 103 responses to browsers for faster page loads | โ Enable |
| Rocket Loader | Defers JavaScript loading to speed up page rendering | โ ๏ธ Test thoroughly (may conflict with page builders) |
| Auto Minify | Deprecated feature (removed August 2024) | โ Ignore |
Rocket Loader Compatibility
Rocket Loader can cause issues with certain WordPress page builders (Elementor, Divi, etc.). If you enable it, thoroughly test all pages and interactive elements. Disable if you encounter JavaScript errors.
4Caching Configuration
Navigate to Caching โ Configuration:
Cache Purging
If changes to your site aren't reflecting, you may need to purge the cache:
- Purge Everything: Clears all cached content (use sparingly)
- Custom Purge: Clear specific URLs, prefixes, or hosts
Caching Level
- Standard: โ Recommended (caches static resources)
- Aggressive: โ ๏ธ May cache too much, breaking dynamic content
Browser Cache TTL
Set to 1 month minimum for optimal performance. This tells browsers how long to cache static resources locally.
Development Mode
Temporarily bypass caching when making significant site changes. Automatically disables after 3 hours.
Smart Tiered Cache Topology
Navigate to Caching โ Tiered Cache:
Enable Smart Tiered Caching
This feature optimizes content delivery by creating a cache hierarchy. When content isn't available in the nearest data center, Cloudflare fetches it from a nearby tier instead of your origin server. Benefits:
- Faster load times for users
- Reduced load on origin server
- Lower bandwidth costs
- Improved cache hit ratios
5Network Configuration
Navigate to Network:
- IPv6 Compatibility: โ Ensure enabled (enabled by default, provides IPv6 support)
- Other settings can remain at defaults
6Scrape Shield
Navigate to Scrape Shield:
| Feature | Protection | Recommendation |
|---|---|---|
| Email Address Obfuscation | Hides email addresses from spam bots | โ Enable |
| Hotlink Protection | Prevents other sites from embedding your images | โ Enable |
5. Automatic Platform Optimization (APO)
๐ฐ Premium Feature - $5/month
APO is Cloudflare's premium WordPress optimization service. While it's not free, the performance benefits make it worthwhile for serious WordPress sites.
What is APO?
Cloudflare's Automatic Platform Optimization (APO) for WordPress is designed to significantly enhance WordPress performance by optimizing content delivery through intelligent caching strategies.
Key Features:
๐ Global CDN Caching
Caches both static AND dynamic HTML content at edge locations worldwide
โก Reduced Server Load
Significantly decreases requests to origin server, reducing hosting costs
๐ฏ Smart Cache Management
Intelligently handles dynamic content and user-specific data
๐ Automatic Purging
Automatically clears cache when content is updated
๐ฑ Mobile Optimization
Enhanced performance for mobile devices
๐ Core Web Vitals
Improves metrics critical for SEO and user experience
How APO Works
Traditional WordPress Caching vs APO
โ Without APO
Visitor Request:
- Request goes to Cloudflare
- Cloudflare only caches static assets (CSS, JS, images)
- HTML request forwarded to your server
- WordPress generates page (database queries, PHP execution)
- Server sends HTML to Cloudflare
- Cloudflare delivers to visitor
Result: Every page view = server processing
โ With APO
Visitor Request:
- Request goes to Cloudflare
- Cloudflare caches EVERYTHING (including HTML)
- HTML served directly from edge cache
- No request to your server
- Instant delivery to visitor
Result: Most page views = instant from cache
APO Implementation
1Enable APO in Dashboard
Navigate to Speed โ Optimization โ Automatic Platform Optimization:
- Click Subscribe to APO ($5/month)
- Enable the APO feature
2Install WordPress Plugin
APO requires the official Cloudflare WordPress plugin for optimal functionality:
- Log into WordPress admin dashboard
- Navigate to Plugins โ Add New
- Search for "Cloudflare"
- Install and activate the Cloudflare plugin
- Configure the plugin with your Cloudflare API token
3Plugin Benefits
The Cloudflare WordPress plugin provides:
- Automatic Cache Purging: Clears Cloudflare cache when you publish/update content
- Smart Cache Invalidation: Only purges affected pages, not entire cache
- WooCommerce Integration: Properly handles e-commerce caching
- Dashboard Integration: Manage Cloudflare settings from WordPress
APO Performance Benefits
| Metric | Without APO | With APO | Improvement |
|---|---|---|---|
| Time to First Byte (TTFB) | 200-600ms | 50-100ms | โก 75-80% faster |
| Full Page Load | 1-3 seconds | 0.3-0.8 seconds | โก 60-75% faster |
| Server CPU Usage | High (every request) | Low (cache hits) | ๐ 90%+ reduction |
| Database Queries | Every page load | Only on cache miss | ๐ 90%+ reduction |
๐ก APO Best Practices
- Disable competing caching plugins: APO replaces server-side page caching (WP Super Cache, W3 Total Cache)
- Keep object caching: Redis/Memcached still beneficial for database queries
- Monitor Core Web Vitals: Use Google Search Console to track improvements
- Test dynamic content: Ensure user-specific content (logged-in users, shopping carts) works correctly
๐ Maintenance & Best Practices
Regular Maintenance Tasks
Monthly Tasks:
- Update Cloudflare IP List: Check for changes at cloudflare.com/ips-v4 and /ips-v6
- Review Security Logs: Check Cloudflare dashboard for blocked threats
- Monitor Performance: Review analytics and Core Web Vitals
- Cache Management: Purge cache after major site updates
Troubleshooting Common Issues
| Issue | Cause | Solution |
|---|---|---|
| Changes not appearing | Cloudflare cache not purged | Purge cache in Cloudflare dashboard or use Development Mode |
| Logs show Cloudflare IPs | Real IP configuration not applied | Verify cloudflare_ip_list.conf is included in server block; reload NGINX |
| SSL errors | Encryption mode mismatch | Ensure Full (Strict) mode; verify server SSL certificate is valid |
| Fail2Ban not working | Blocking Cloudflare IPs instead of visitors | Ensure real IP configuration is correct; Fail2Ban should see visitor IPs |
| Rocket Loader breaks site | JavaScript conflicts | Disable Rocket Loader; test incrementally with different page builders |
Testing Checklist
After Cloudflare Implementation:
- โ Verify site loads correctly via HTTPS
- โ Check HTTP redirects to HTTPS automatically
- โ Confirm logs show real visitor IPs (not Cloudflare IPs)
- โ Test dynamic content (user logins, shopping carts, comments)
- โ Verify forms submit correctly
- โ Check admin dashboard accessibility
- โ Test from multiple devices and browsers
- โ
Use curl to verify headers:
curl -I https://example.com - โ Monitor Fail2Ban logs for correct IP detection
- โ Run speed tests (GTmetrix, PageSpeed Insights)
๐ฏ Summary
Implementing Cloudflare with proper NGINX configuration provides substantial benefits for WordPress hosting:
โ Security
- DDoS protection
- Bot mitigation
- IP masking
- SSL/TLS encryption
โ Performance
- Global CDN
- Edge caching
- Faster TTFB
- Reduced server load
โ Reliability
- Always Online mode
- Load balancing
- Uptime monitoring
- Failover protection
๐ Key Takeaways
- Implement after site setup: Cloudflare adds complexity; complete your site first
- Enable 2FA: Secure your Cloudflare account with two-factor authentication
- Configure Real IP: Essential for proper logging and security tools
- Use Full (Strict) SSL: Maximum security with end-to-end encryption
- Test thoroughly: Verify all functionality after enabling Cloudflare
- Manual IP updates: Don't automate Cloudflare IP list downloads
- Consider APO: $5/month investment for significant performance gains
- Monitor regularly: Review logs, analytics, and performance metrics