15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
10.10.2024

How to Fix Cloudflare Error 520: Complete Diagnostic and Resolution Guide

Cloudflare Error 520 is an HTTP status code returned when Cloudflare's edge network receives an empty, unexpected, or otherwise uninterpretable response from your origin server. Unlike a 502 or 504, which indicate a gateway timeout or bad gateway, a 520 is Cloudflare's catch-all for responses that fall outside any recognized HTTP specification β€” meaning the origin server technically responded, but what it sent back was invalid, truncated, or structurally malformed.

From a practical standpoint, Error 520 means the TCP connection between Cloudflare and your origin server was established, but the HTTP-layer handshake broke down. The user sees a Cloudflare-branded error page with the message "Web server is returning an unknown error" β€” and your site is effectively offline for them.

What Triggers Error 520: Root Causes Explained

Understanding the exact failure mode is essential before touching any configuration. Error 520 is not a single problem β€” it is a symptom class. The following causes are the most common, ranked by frequency in production environments.

Origin server returning an empty response body with no HTTP status line. This is the most frequent trigger. Apache or Nginx may crash mid-response, leaving Cloudflare holding an open TCP socket with no data arriving.

Firewall or security software blocking Cloudflare's IP ranges. Tools like ModSecurity, Fail2Ban, CSF (ConfigServer Security & Firewall), or application-layer plugins such as Wordfence can silently drop packets from Cloudflare's egress IPs, causing the connection to reset without a proper HTTP response.

SSL/TLS handshake mismatch between Cloudflare and the origin. If Cloudflare is set to "Full (Strict)" mode but your origin server has an expired, self-signed, or misconfigured certificate, the TLS negotiation fails before any HTTP data is exchanged.

Malformed or oversized HTTP response headers. Cloudflare enforces a hard limit of 32 KB on response headers. Any single header or combined header set exceeding this limit causes a 520. This is a common edge case with poorly written PHP applications that dump large session data or debug output into headers.

Origin server process crash or OOM (Out-of-Memory) kill. If the web server worker process (e.g., an Nginx worker or PHP-FPM pool) is killed by the Linux OOM killer mid-request, the connection drops abruptly.

Application-level exceptions before headers are sent. A fatal PHP error, an unhandled Python exception, or a Node.js crash that occurs before res.writeHead() is called results in an empty response that Cloudflare cannot parse.

Connection reset by origin (TCP RST). The origin server actively resets the TCP connection, which Cloudflare interprets as an unknown response.

Error 520 vs. Other Cloudflare 5xx Errors

Distinguishing 520 from similar Cloudflare errors prevents wasted diagnostic effort.

Error CodeMeaningPrimary Cause
520Unknown/unexpected response from originEmpty response, malformed headers, TCP RST
521Origin server refused connectionOrigin web server is down; port 80/443 not listening
522Connection timed outOrigin took too long to accept the TCP connection
523Origin is unreachableDNS resolution failure or routing issue to origin IP
524A timeout occurredTCP connected but origin took too long to respond
525SSL handshake failedTLS certificate mismatch or cipher incompatibility
526Invalid SSL certificateOrigin certificate not trusted by Cloudflare
502/504Bad/Gateway timeoutUpstream proxy or load balancer failure

If you are seeing 521, your web server process is not running. If you are seeing 524, your application is running but too slow. If you are seeing 520, the server is running and responding β€” but what it sends back is broken.

Step-by-Step Fix for Error 520

Step 1: Verify Origin Server Health and Connectivity

Before touching Cloudflare, confirm the origin server is alive and the web server daemon is running.

Check if the web server process is active:

# For Nginx
sudo systemctl status nginx

# For Apache
sudo systemctl status apache2

# For LiteSpeed
sudo systemctl status lsws

Test direct connectivity to the origin IP, bypassing Cloudflare's proxy. Retrieve your origin IP from the Cloudflare DNS dashboard, then test it directly:

curl -I --resolve yourdomain.com:80:YOUR_ORIGIN_IP http://yourdomain.com/
curl -I --resolve yourdomain.com:443:YOUR_ORIGIN_IP https://yourdomain.com/

If curl returns a valid HTTP status (200, 301, etc.), the origin server is functional and the issue is in the Cloudflare-to-origin communication layer. If curl returns an empty reply or a connection reset, the problem is on the origin side.

Check system resource pressure:

# Memory usage
free -h

# CPU load
uptime

# Check for OOM kills in the last boot
dmesg | grep -i "oom|killed process"

# Check for PHP-FPM pool exhaustion
sudo systemctl status php8.1-fpm

Step 2: Inspect Origin Server Error Logs

The origin server logs are the single most valuable diagnostic source. Do not skip this step.

For Nginx:

sudo tail -n 100 /var/log/nginx/error.log
sudo tail -n 100 /var/log/nginx/access.log

For Apache:

sudo tail -n 100 /var/log/apache2/error.log
sudo tail -n 100 /var/log/apache2/access.log

Look specifically for:

    [crit] or [emerg] level entries
    upstream prematurely closed connection (Nginx + PHP-FPM)
    Premature end of script headers (Apache + CGI/PHP)
    worker_connections are not enough (Nginx worker limit hit)
    PHP fatal errors logged to the web server error log
    
    Cross-reference log timestamps with when the 520 errors occurred. Cloudflare's dashboard under Analytics > Traffic shows 520 spike timestamps you can use for correlation.
    Step 3: Whitelist Cloudflare IP Ranges in Your Firewall
    If a firewall is blocking Cloudflare's egress IPs, the connection will be reset silently. Cloudflare publishes its current IP ranges at https://www.cloudflare.com/ips/.
    For UFW (Ubuntu/Debian):
    # Download Cloudflare IPv4 ranges and whitelist them
    for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
      sudo ufw allow from $ip to any port 80,443 proto tcp
    done
    
    # Repeat for IPv6
    for ip in $(curl -s https://www.cloudflare.com/ips-v6); do
      sudo ufw allow from $ip to any port 80,443 proto tcp
    done
    
    sudo ufw reload
    For CSF (ConfigServer Firewall):
    Add Cloudflare's IP ranges to /etc/csf/csf.allow, then restart CSF:
    sudo csf -r
    For ModSecurity: If you suspect ModSecurity is the culprit, check its audit log:
    sudo tail -n 200 /var/log/modsec_audit.log
    Look for rule matches against Cloudflare IP addresses. You can whitelist Cloudflare IPs in your ModSecurity configuration or set the SecRemoteRules directive to exclude them.
    Critical note: Never permanently disable your firewall or ModSecurity. Whitelist only Cloudflare's published IP ranges, and re-enable all security controls immediately after testing.
    Step 4: Audit and Fix HTTP Response Headers
    Malformed or oversized headers are a frequently overlooked cause of 520 errors. Use curl with verbose output to inspect exactly what your origin is sending:
    curl -v --resolve yourdomain.com:443:YOUR_ORIGIN_IP https://yourdomain.com/ 2>&1 | head -80
    Watch for:
    
    Headers with non-ASCII characters or control characters
    Set-Cookie headers with extremely long values (common in PHP session misconfigurations)
    Missing or malformed Content-Type headers
    Duplicate Content-Length headers with conflicting values
    
    If you are running a PHP application, check php.ini for output_buffering settings. A disabled output buffer combined with a fatal error mid-response can cause partial header transmission.
    For WordPress sites specifically: Plugins that inject large amounts of data into HTTP headers (some security or caching plugins do this) can push header size past Cloudflare's 32 KB limit. Audit active plugins and test in safe mode.
    Step 5: Validate Cloudflare SSL/TLS Configuration
    An SSL mismatch between Cloudflare and the origin is a common source of 520-class failures that masquerades as a generic unknown error.
    Navigate to Cloudflare Dashboard > SSL/TLS > Overview and verify the encryption mode:
    
    
    
    Cloudflare SSL Mode
    Origin Requirement
    Recommended For
    
    
    
    
    
    
    
    
    —
    —
    —
    
    
    
    
    
    
    
    
    Off
    No SSL on origin
    Never recommended
    
    
    
    
    
    
    
    
    Flexible
    No SSL needed on origin
    Legacy setups only; security risk
    
    
    
    
    
    
    
    
    Full
    Any SSL cert on origin (including self-signed)
    Dev environments
    
    
    
    
    
    
    
    
    Full (Strict)
    Valid, trusted SSL cert on origin
    All production sites
    
    
    
    
    
    If your origin uses a self-signed certificate and Cloudflare is set to Full (Strict), the TLS handshake will fail. Either install a valid certificate on the origin (a free Let's Encrypt certificate works) or switch to Full mode temporarily while you fix the certificate.
    If you need a properly trusted certificate for your origin server, SSL Certificates from a trusted CA eliminate the self-signed certificate problem entirely and are compatible with Cloudflare's Full (Strict) mode.
    Step 6: Pause Cloudflare Proxy for Targeted Diagnosis
    Temporarily removing Cloudflare from the request path isolates whether the problem is in Cloudflare's configuration or on the origin server.
    Method 1: Disable proxy on a specific DNS record
    In the Cloudflare DNS dashboard, click the orange cloud icon next to your A or CNAME record to turn it gray. This bypasses Cloudflare's proxy while keeping DNS resolution through Cloudflare. DNS propagation takes up to 5 minutes.
    Method 2: Pause Cloudflare globally for the domain
    Navigate to Cloudflare Dashboard > Overview > Advanced Actions > Pause Cloudflare on Site. This routes all traffic directly to your origin.
    After pausing, test your site. If it loads correctly, the issue is in Cloudflare's configuration. If it still fails, the problem is on the origin server regardless of Cloudflare.
    Re-enable Cloudflare immediately after testing β€” a paused Cloudflare means your site loses DDoS protection, CDN caching, and WAF coverage.
    Step 7: Check DNS Record Accuracy
    A misconfigured DNS A record pointing to a wrong or stale IP address causes Cloudflare to proxy traffic to the wrong server, which will return an unexpected response.
    In the Cloudflare DNS dashboard:
    
    Verify that the A record for your root domain (@) points to your current origin server IP
    Verify that the CNAME for www resolves correctly
    If you recently migrated servers, confirm the old IP is no longer referenced anywhere
    
    Confirm what IP Cloudflare is actually sending traffic to:
    dig +short yourdomain.com @1.1.1.1
    Compare this against your actual origin server IP. If they differ, update the DNS record in Cloudflare.
    Step 8: Scale Origin Server Resources
    If your origin server is consistently under high load, 520 errors will occur intermittently during traffic spikes as worker processes become exhausted and connections are dropped.
    Diagnose resource exhaustion:
    # Check Nginx worker connections
    sudo nginx -T | grep worker_connections
    
    # Check PHP-FPM pool limits
    cat /etc/php/8.1/fpm/pool.d/www.conf | grep -E "pm.|max_children"
    
    # Monitor real-time connections
    ss -s
    Tuning options without a hardware upgrade:
    
    Increase worker_connections in /etc/nginx/nginx.conf
  • Increase pm.max_children in the PHP-FPM pool configuration
  • Enable Nginx's keepalive directive for upstream connections
  • Implement object caching (Redis or Memcached) to reduce database pressure
  • Enable Cloudflare's Cache Everything page rule to offload static asset delivery

For applications that have outgrown shared infrastructure, migrating to a VPS Hosting environment gives you full control over worker process limits, memory allocation, and kernel-level TCP tuning β€” none of which are available on shared plans.

If your application handles compute-intensive workloads (ML inference, video processing, large dataset operations) that cause intermittent worker crashes, GPU Hosting offloads those tasks from your web server processes, eliminating a common source of mid-response crashes.

Step 9: Review Cloudflare Firewall and Security Rules

Cloudflare's own security features can occasionally interfere with legitimate origin communication, particularly if custom Firewall Rules or WAF rules are misconfigured.

Check Cloudflare Dashboard > Security > WAF > Custom Rules for any rules that might be intercepting requests before they reach the origin. Also review Security > Settings > Browser Integrity Check β€” in rare cases, this can cause unexpected behavior with certain user agents or automated requests.

Review the Security > Events log to see if Cloudflare is blocking or challenging requests that should be reaching your origin.

Step 10: Escalate to Your Hosting Provider or Cloudflare Support

If all the above steps have been exhausted without resolution, escalate with precise information.

When contacting your hosting provider, provide:

  • The exact timestamps of 520 occurrences (from Cloudflare Analytics)
  • Relevant excerpts from your web server error log
  • The output of curl -v against your origin IP
  • Current resource usage metrics (CPU, RAM, connection count)

Providers running managed infrastructure on Dedicated Servers can perform kernel-level diagnostics, packet captures (tcpdump), and socket-level inspection that are not available on shared environments.

When contacting Cloudflare Support, include:

  • Your Ray ID from the 520 error page (visible in the Cloudflare error HTML)
  • A HAR file captured from Chrome DevTools during the error
  • Your current SSL/TLS mode and any custom Firewall Rules

The Ray ID is critical β€” it allows Cloudflare's engineers to pull the exact edge node log entry for your failed request.

Advanced Diagnostic: Capturing the Exact Failure with tcpdump

For persistent or intermittent 520 errors that resist standard troubleshooting, a packet capture on the origin server reveals exactly what is happening at the TCP/HTTP layer when Cloudflare connects.

# Capture traffic from Cloudflare IPs on port 443
sudo tcpdump -i eth0 -w /tmp/cloudflare_capture.pcap 'src net 103.21.244.0/22 or src net 103.22.200.0/22 or src net 103.31.4.0/22 or src net 104.16.0.0/13 or src net 104.24.0.0/14' and port 443

Open the resulting .pcap file in Wireshark and filter for tcp.flags.reset == 1 to identify TCP RST packets, which indicate the origin is actively resetting connections. Filter for http to inspect any partial HTTP responses being sent.

This level of analysis definitively identifies whether the 520 is caused by a firewall RST, an application crash mid-response, or a TLS failure.

Preventing Error 520: Proactive Measures

Reactive troubleshooting is expensive. These measures reduce 520 occurrence probability significantly.

Implement Cloudflare Health Checks. Under Traffic > Health Checks, configure a health check against your origin. Cloudflare will alert you before users start seeing 520 errors.

Enable Cloudflare's Always Online feature (under Caching > Configuration). While it does not fix the underlying issue, it serves cached versions of your pages to users during origin outages, preventing a complete service blackout.

Set up origin server monitoring with tools like UptimeRobot, Pingdom, or a self-hosted solution like Uptime Kuma. Monitor the origin IP directly (not the Cloudflare-proxied domain) to detect origin failures independently of Cloudflare.

Automate Cloudflare IP whitelisting. Cloudflare's IP ranges change occasionally. Use a cron job to refresh your firewall whitelist:

# /etc/cron.weekly/update-cloudflare-ips
#!/bin/bash
CF_IPS=$(curl -s https://www.cloudflare.com/ips-v4)
# Add logic to update UFW/CSF/iptables rules

Use Cloudflare's Authenticated Origin Pulls. This feature configures your origin to only accept HTTPS connections that present Cloudflare's client certificate, blocking any direct-to-origin requests that bypass the proxy. This also eliminates a class of 520 errors caused by non-Cloudflare traffic hitting your origin and triggering security software responses.

For teams managing multiple domains and web applications, a VPS with cPanel provides centralized log access, firewall management, and SSL certificate management across all hosted domains β€” significantly reducing the time-to-diagnosis for 520 events.

Decision Matrix: Diagnosing Your Specific 520 Scenario

SymptomMost Likely CauseFirst Action
520 on all pages, all users, suddenlyOrigin server crash or OOM killCheck `systemctl status nginx/apache2`, review `dmesg`
520 intermittently, under loadWorker process exhaustionIncrease `pm.max_children` or `worker_connections`
520 only on HTTPS, not HTTPSSL/TLS mismatchVerify Cloudflare SSL mode vs. origin certificate
520 after enabling a new plugin/moduleMalformed headers or fatal errorCheck error log, test with plugin disabled
520 after server migrationStale DNS A recordVerify A record IP in Cloudflare DNS dashboard
520 after firewall rule changeCloudflare IPs blockedWhitelist Cloudflare IP ranges in firewall
520 with TCP RST in packet captureFirewall actively resetting connectionsAudit iptables/CSF/UFW rules
520 only for specific URLsApplication-level exceptionCheck application error log for that route

Technical Key-Takeaway Checklist

Before escalating to support, confirm you have completed each of the following:

  • Verified the origin web server process is running (systemctl status)
  • Tested direct origin connectivity with curl -v --resolve bypassing Cloudflare
  • Reviewed origin error logs for the exact timestamps of 520 events
  • Confirmed Cloudflare IP ranges are whitelisted in all active firewalls (UFW, CSF, iptables, ModSecurity)
  • Validated that response headers are under 32 KB and contain no malformed values
  • Confirmed Cloudflare SSL/TLS mode matches the origin certificate type
  • Verified DNS A records point to the correct, current origin IP
  • Checked system memory and CPU for OOM kills or resource exhaustion
  • Captured the Ray ID from the 520 error page for Cloudflare support escalation
  • Reviewed Cloudflare Security Events log for WAF rule interference

Frequently Asked Questions

What is the difference between Cloudflare Error 520 and Error 521?

Error 521 means Cloudflare successfully reached your origin server's IP but the web server process refused the TCP connection β€” typically because Nginx or Apache is not running. Error 520 means the TCP connection was established but the HTTP response was empty, truncated, or malformed. If you see 521, start your web server. If you see 520, the server is running but sending broken responses.

Can Error 520 be caused by Cloudflare itself, not the origin server?

Rarely, but yes. Cloudflare edge node issues can cause 520 errors that are not reproducible when accessing the origin directly. Check cloudflarestatus.com for active incidents. If the origin responds correctly via direct curl and Cloudflare's status page shows an active incident, wait for Cloudflare to resolve it rather than making changes to your server.

Why does Error 520 happen only intermittently and not consistently?

Intermittent 520 errors almost always indicate resource exhaustion β€” PHP-FPM worker pools running out of available children, Nginx hitting worker_connections limits, or the Linux OOM killer terminating processes under memory pressure. These conditions occur under load spikes and resolve when traffic drops, creating the intermittent pattern. Consistent 520 errors point to a configuration problem.

Does pausing Cloudflare fix Error 520?

Pausing Cloudflare removes it from the request path, so if your site works after pausing, the problem is in Cloudflare's configuration (SSL mode, WAF rules, DNS records). If your site still fails after pausing, the problem is on the origin server. Pausing Cloudflare is a diagnostic step, not a fix β€” it removes DDoS protection and CDN caching while active.

How do I find the Ray ID to report a 520 error to Cloudflare?

The Ray ID is displayed at the bottom of the Cloudflare 520 error page shown to users. It looks like a 16-character hexadecimal string (e.g., 7a3f2b9c1d4e8f0a). You can also find it in the CF-Ray response header, visible in Chrome DevTools under the Network tab. Always include this ID when opening a Cloudflare support ticket β€” it allows Cloudflare engineers to retrieve the exact edge log entry for your failed request.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started