Cloudflare for Website Owners: DNS, SSL, Caching, and 5xx Troubleshooting Guide
Architecture Overview: Cloudflare as a Reverse Proxy
Cloudflare functions as a reverse proxy, positioning its global edge network directly between website visitors and the origin web server. When a client issues an HTTP/S request for a domain using Cloudflare, the request does not connect directly to the underlying host. Instead, Anycast DNS routes the traffic to the nearest Cloudflare edge data center. The edge evaluates Web Application Firewall (WAF) rules, inspects TLS negotiation, verifies cache availability, and—if the asset cannot be served from memory or disk—initiates a secondary connection upstream to the origin server.
Operating a site behind a reverse proxy introduces two independent connection segments:
- Client-to-Cloudflare: The connection between the visitor's browser and the Cloudflare edge.
- Cloudflare-to-Origin: The upstream connection between the Cloudflare edge and the hosting server.
Understanding this separation is critical. An error returned to the browser does not automatically mean the edge is broken, nor does a healthy local testing curl command mean the edge can establish an upstream session. System administrators must isolate whether an anomaly originates at the visitor layer, the edge proxy, or the upstream application stack.
DNS Fundamentals & Proxy Status Demystified
The core mechanism routing traffic through the edge is the proxy status of DNS records managed in the Cloudflare dashboard. For any address (A, AAAA, or CNAME) record, Cloudflare provides two operational modes:
- Proxied (Orange Cloud): Authoritative DNS queries for the domain resolve to Cloudflare Anycast IP addresses. Web traffic routes through the edge network, enabling caching, WAF inspection, DDoS mitigation, and edge SSL termination.
- DNS-Only / Unproxied (Grey Cloud): DNS queries resolve directly to the destination origin IP address or target host. Traffic bypasses edge features, connecting the visitor straight to the server.
Warning: Switching an active production host from Proxied to DNS-Only exposes the origin's direct IP address in public DNS records. Once an origin IP is exposed, malicious actors can bypass Cloudflare security rules and target the origin directly with Layer 7 attacks unless firewall ACLs enforce access strictly from Cloudflare IP ranges.
Full Zone Setup vs. Partial (CNAME) Setup
Cloudflare supports two authoritative configurations:
- Full Zone Delegation: The domain registrar delegates nameservers entirely to Cloudflare (e.g.,
ns1.cloudflare.com). Cloudflare becomes the authoritative DNS provider for the zone, managing all zone records directly. - Partial (CNAME) Setup: Authoritative DNS remains at a third-party provider (e.g., Route 53, BIND), and specific subdomains point to Cloudflare via CNAME records. This mode is reserved for Business and Enterprise plans and requires manual record synchronization.
Safe Operations for Non-HTTP Services
Cloudflare's standard HTTP proxy handles web traffic on designated HTTP/HTTPS ports (such as 80, 443, 8080, 8443). Non-HTTP services—including mail protocols (SMTP, IMAP, POP3), SSH, SFTP, and FTP—cannot pass through standard HTTP proxy records. Setting an orange-cloud proxy on an A record used for mail.example.com or ssh.example.com will break mail delivery and shell access. Always keep mail (MX targets) and direct administrative subdomains set to DNS-Only (Grey Cloud).
SSL/TLS Encryption Modes and Origin Certificates
Configuring SSL/TLS incorrectly in Cloudflare is the single most common cause of redirect loops (ERR_TOO_MANY_REDIRECTS) and handshake failures. Cloudflare categorizes origin TLS requirements into distinct modes:
| SSL/TLS Mode | Client-to-Edge Encryption | Edge-to-Origin Encryption | Origin Certificate Validation | Security Posture |
|---|---|---|---|---|
| Off | No (Plain HTTP) | No (Plain HTTP) | None | Insecure. Completely unencrypted. |
| Flexible | Yes (HTTPS) | No (Plain HTTP on Port 80) | None | Insecure backchannel. Vulnerable to MITM; causes redirect loops if origin forces HTTPS. |
| Full | Yes (HTTPS) | Yes (HTTPS on Port 443) | No validation (accepts self-signed) | Encrypted upstream, but vulnerable to spoofing without CA validation. |
| Full (Strict) | Yes (HTTPS) | Yes (HTTPS on Port 443) | Enforces valid, non-expired public or Cloudflare Origin CA certificate | Industry standard best practice for end-to-end transport security. |
Warning: Never select Flexible mode if your origin web server or application stack (such as WordPress, Nginx, or Apache) contains rules redirecting HTTP requests to HTTPS. In Flexible mode, Cloudflare connects to your origin over port 80. If the origin responds with an HTTP 301/302 redirect back to HTTPS, Cloudflare accepts it, sends the redirect to the client, and receives another incoming HTTPS request—triggering an infinite redirect loop.
Deploying Cloudflare Origin CA Certificates
To implement Full (Strict) effortlessly without managing short-lived public Let's Encrypt renewal challenges on the origin, use a Cloudflare Origin CA Certificate. Cloudflare generates free, long-lived (up to 15 years) certificates explicitly trusted by the Cloudflare edge.
To verify the origin's certificate and TLS response directly from your workstation—bypassing Cloudflare's edge—execute the following OpenSSL command:
openssl s_client -connect ORIGIN_IP:443 -servername example.comWhy this matters: Replacing ORIGIN_IP with the direct public IP of your server forces the connection directly to your web server while sending the proper Server Name Indication (SNI). If this command fails or returns a handshake timeout, your origin web server configuration is the point of failure, not Cloudflare.
Edge Redirects vs. Origin Redirects
Redirect rules should be enforced as close to the user as possible to reduce latency, save origin compute resources, and prevent cascading hops. Cloudflare provides native tools to handle redirects at the edge:
- Always Use HTTPS: Automatically redirects all incoming plain
http://requests tohttps://with a 301 redirect directly at the edge, terminating unencrypted requests before they reach the origin. - Redirect Rules (Dynamic/Static URL Redirects): Replaces legacy Page Rules for canonical domain mapping (e.g., redirecting
example.com/*tohttps://www.example.com/$1or stripping subpaths).
Preventing Redirect Loops
Redirect loops happen when edge configurations clash with origin configurations. To avoid infinite loops:
- If Always Use HTTPS is enabled on Cloudflare, ensure your origin application does not attempt to detect protocol status solely from the internal TCP socket (which might appear as HTTP if an upstream reverse proxy terminates SSL). Configure the application to read the
X-Forwarded-Proto: httpsheader. - Set the SSL/TLS mode to Full (Strict) so that Cloudflare consistently forwards upstream requests over HTTPS.
- Check that no edge redirect rule matches the identical destination URL it outputs.
Caching Architecture, Purging, and Development Mode
Cloudflare caches static assets based on file extensions (e.g., CSS, JS, JPG, PNG, WEBP, PDF) by default, while dynamic HTML and JSON responses pass straight to the origin unless explicitly governed by Cache Rules.
Inspecting the CF-Cache-Status Header
Every response proxied through Cloudflare contains a CF-Cache-Status response header. Inspecting this header reveals edge cache behavior:
HIT: The asset was served directly from the Cloudflare edge cache datacenter.MISS: The asset was not found in edge cache; it was fetched from the origin and stored for future requests.BYPASS: Cloudflare was instructed to bypass cache due to a Cache Rule, Page Rule, or cache-control private header.EXPIRED: The cached asset exceeded its edge Time-to-Live (TTL) and was revalidated with the origin.DYNAMIC: The default state for non-static extensions (like HTML documents). Cloudflare did not attempt to cache the asset and fetched it live from the origin.
Development Mode vs. Cache Purge Strategies
When deploying code or debugging stylesheets, avoid indiscriminate cache purges. Use the appropriate invalidation mechanism:
| Method | Mechanism | Impact on Origin Server | Recommended Use Case |
|---|---|---|---|
| Development Mode | Temporarily bypasses edge cache for 3 hours; serves assets directly from origin. | High (all edge requests pass to origin). | Active theme development, troubleshooting live CSS/JS changes. |
| Single-File / URL Purge | Purges exact, individual asset URLs across all edge data centers. | Negligible (targeted re-fetches). | Production code deployments updating specific JS/CSS bundles. |
| Cache-Tag / Prefix Purge | Purges groups of content matching custom headers or path prefixes (e.g., /static/assets/). | Low to moderate. | Granular CMS invalidation and API route cache management. |
| Purge Everything | Instantly invalidates the entire cache across the global zone. | Critical (Causes severe cache stampede). | Emergency sitewide rollback or structural domain-level redesigns. |
Warning: Executing a Purge Everything command on a high-traffic production store or media publication drops edge cache hit ratios to zero instantly. The sudden surge of concurrent requests hitting the origin web server simultaneously—known as a cache stampede or thundering herd problem—can overwhelm database pools and crash origin web services. Reserve full purges for critical emergencies.
Definitive 5xx Error Diagnostic and Resolution Guide
Cloudflare 5xx errors indicate a failure in the communication pipeline between the visitor, Cloudflare edge proxies, and the origin server. Use the following decision workflows to diagnose and resolve each specific status code.
Diagnostic Framework: The cf-ray Header and Origin Validation
Every error screen generated by Cloudflare includes a unique Ray ID (e.g., Ray ID: 89ab34cd56ef7890). When auditing server logs, search for the incoming cf-ray header value to correlate the edge request with your origin's access and error logs.
To test origin responsiveness directly without modifying public DNS records, run this curl command with the --resolve flag:
curl -Iv https://example.com/login --resolve example.com:443:ORIGIN_IPWhy this matters: This command forces your local machine to route the HTTPS request for example.com directly to ORIGIN_IP over TLS, preserving the HTTP Host header and SNI negotiation without relying on Cloudflare's edge proxy. If this test fails, the issue resides entirely within your origin infrastructure.
Error 520: Web Server Is Returning an Unknown Error
What it means: The Cloudflare edge reached the origin, but the origin returned an empty, malformed, or invalid response that violates HTTP protocol specifications.
- Common Causes: Origin web application crashes (frequently PHP-FPM segfaults), upstream connection resets, response headers exceeding Cloudflare's 128 KB header limit (often caused by run-away session cookies), or malformed HTTP/2 framing.
- Resolution Workflow:
- Check origin web server error logs (
/var/log/nginx/error.log,/var/log/apache2/error.log, or PHP-FPM error logs) for crashes occurring at the exact timestamp of the Ray ID. - Inspect the size of response headers returned by the origin application using the direct
curl -Iv --resolvecommand. If headers exceed 128 KB, reduce cookie volumes or truncate redundant headers. - If the origin uses HTTP/2 upstream, verify the protocol stability or navigate in Cloudflare to Speed > Settings > Protocol Optimization and disable HTTP/2 to Origin to test protocol compatibility.
- Check origin web server error logs (
Error 521: Web Server Is Down
What it means: The Cloudflare edge attempted a TCP connection to the origin on the requested port (80 or 443), but the origin server actively refused the connection (TCP RST).
- Common Causes: The web daemon (Nginx, Apache, Caddy, IIS) is stopped or crashed, or origin host-based firewalls (such as
iptables,ufw, or Fail2ban) are blocking Cloudflare IP addresses. - Resolution Workflow:
- Log in to your origin server and verify the service status:
sudo systemctl status nginxorsudo systemctl status apache2. - Confirm the process is listening on the expected ports:
sudo ss -tulpn | grep -E ':(80|443)'. - Audit your firewall rules. Ensure all official Cloudflare IP ranges are explicitly allowlisted and not rate-limited or dropped by security daemons.
- Log in to your origin server and verify the service status:
Error 522: Connection Timed Out
What it means: Cloudflare was unable to complete the TCP three-way handshake (SYN, SYN-ACK, ACK) with the origin server within the timeout window.
- Common Causes: Network routing drops, packet filtering dropping SYN packets silently at the origin perimeter/cloud security group (e.g., AWS Security Groups, Google Cloud VPC firewalls), or extreme server resource exhaustion (CPU/RAM saturation locking the kernel backlog).
- Resolution Workflow:
- Verify cloud infrastructure firewalls (AWS Security Groups, Azure NSG, Hetzner Firewall) allow inbound traffic on ports 80/443 from all Cloudflare IP blocks.
- Check server load and memory pressure via
htoportopto verify whether the system is out of memory (OOM) or dropping connections. - Verify your origin server has
Keep-Aliveenabled in the HTTP configuration to support persistent edge-to-origin connections.
Error 523: Origin Is Unreachable
What it means: Cloudflare cannot route network traffic to the origin IP address due to an invalid routing path or missing DNS record.
- Common Causes: An incorrect or obsolete IP address entered in the Cloudflare DNS dashboard, an authoritative BGP routing failure between the edge and the origin ISP, or an unrouted private IP address (e.g.,
192.168.x.xor10.x.x.x) assigned to a proxied public record. - Resolution Workflow:
- Review your Cloudflare DNS app. Confirm the
AorAAAArecord points to the active, publicly routable IP address of your origin server. - Contact your hosting provider to verify that upstream BGP routing prefixes for your subnet are properly announced across global transit providers.
- Review your Cloudflare DNS app. Confirm the
Error 524: A Timeout Occurred
What it means: Cloudflare successfully established a TCP connection with the origin and sent the HTTP request, but the origin server failed to return an HTTP response before the 100-second (default) Proxy Read Timeout expired.
- Common Causes: Long-running database queries, heavy server-side reporting scripts, background PDF generation, complex batch jobs executed directly via synchronous HTTP requests, or origin worker pool exhaustion.
- Resolution Workflow:
- Optimize slow database queries and execution routines serving the targeted URL.
- Offload long-running operations (data exports, reports) to asynchronous background workers (e.g., Redis queues, Celery, Laravel Queues) that return an immediate
202 Acceptedresponse to the client. - Move administrative or heavy batch endpoints to a separate subdomain set to DNS-Only (Grey Cloud) to bypass the edge proxy read timeout limit.
Error 525: SSL Handshake Failed
What it means: The TCP connection succeeded, but the TLS/SSL cryptographic handshake between Cloudflare and the origin server failed while SSL/TLS mode was set to Full or Full (Strict).
- Common Causes: The origin server does not have an active SSL certificate installed, does not support Server Name Indication (SNI), lacks matching modern cipher suites, or port 443 is misconfigured.
- Resolution Workflow:
- Run
openssl s_client -connect ORIGIN_IP:443 -servername example.comto inspect origin TLS status. - Ensure the origin web server configuration contains a valid TLS certificate and is listening for secure traffic on port 443.
- Verify that your origin server supports cipher suites compatible with Cloudflare's edge TLS termination.
- Run
Error 526: Invalid SSL Certificate
What it means: The domain is configured with Full (Strict) SSL/TLS mode, but the certificate presented by the origin server is untrusted or invalid.
- Common Causes: The origin certificate has expired, is self-signed (without being an official Cloudflare Origin CA certificate), or does not match the Subject Alternative Name (SAN) for the requested domain name.
- Resolution Workflow:
- Inspect the validity dates and SANs of the origin certificate using
openssl s_client. - If the origin certificate is self-signed or untrusted, replace it with a valid certificate from a trusted public CA (like Let's Encrypt) or generate and install a free Cloudflare Origin CA Certificate directly via the SSL/TLS dashboard.
- Ensure the domain name requested matches the Common Name (CN) or SAN extensions present on the certificate.
- Inspect the validity dates and SANs of the origin certificate using
Verification and Rollback Runbook
Before applying structural DNS, security, or caching modifications, establish a disciplined change management workflow to protect availability.
Pre-Change Checklist
- Document existing DNS record targets, TTL values, and current SSL/TLS modes.
- Ensure you have out-of-band administrative access to your origin server (e.g., via SSH using a direct IP or console provider access) that does not depend on proxied records.
- Validate origin web server operational health locally using direct IP queries.
Step-by-Step Change Execution
- Make incremental changes: Modify one setting at a time (e.g., switch SSL mode from Full to Full (Strict), or modify a single Cache Rule).
- Test using direct requests: Verify that the origin server satisfies the technical requirements of the new edge configuration before enabling it at the edge.
- Purge target assets selectively: Use URL-level or prefix purges to clear stale responses without purging the entire zone cache.
Post-Change Verification
Execute real-time synthetic requests against the Cloudflare edge to verify HTTP status codes, SSL negotiation, and cache state:
curl -Iv https://example.com/Confirm the response headers show:
HTTP/2orHTTP/3200 OKstatus.CF-Rayindicating traffic routed through the expected edge location.- Expected
CF-Cache-Status(e.g.,HIT,MISS, orDYNAMIC). - Correct security headers (e.g.,
Strict-Transport-Security).
Emergency Rollback Procedures
If an update causes outages or unanticipated 5xx errors across production traffic:
- Immediate SSL Loop / 525 / 526 Errors: Revert the SSL/TLS mode in the dashboard back to its previous working state (e.g., return to Full from Full (Strict)) while fixing origin certificates.
- Persistent Origin Connectivity Outage (521/522/523): If Cloudflare cannot reach the origin during a critical launch and origin services are verified healthy, set the affected DNS record to DNS-Only (Grey Cloud). This bypasses the edge proxy and routes visitor DNS directly to the origin host while routing or firewall ACL issues are diagnosed.
- Cache Corruption: If incorrect content is cached at the edge, execute a targeted URL or Prefix purge for the affected endpoints immediately.