520 Error Code: Causes, Fixes, and How to Prevent It
Cloudflare returns a 520 error code when it reaches a website's origin server but receives an empty, malformed, or otherwise unusable HTTP response. Unlike a standard 500 error, 520 is Cloudflare-specific: it identifies a failure in the Cloudflare-to-origin exchange, not its exact cause.
This guide shows you how to identify that cause, fix the failing layer, and prevent repeat errors, whether you operate the site or encounter 520 errors while scraping or crawling.
TL;DR
- Cloudflare returns 520 when it contacts an origin but receives an empty, malformed, or otherwise unusable HTTP response.
- The Internet Assigned Numbers Authority (IANA) doesn't register 520 as a standard HTTP status code; Cloudflare uses it for failures its edge can't classify more precisely.
- Origin crashes, blocked Cloudflare IPs, response headers over 128 KB, malformed output, and HTTP/2 or Authenticated Origin Pull misconfiguration commonly cause 520.
- Compare OriginResponseStatus with CacheStatus, review origin logs, and test the origin directly before changing firewall, header, or protocol settings.
What is a 520 error code?
Cloudflare labels 520 as "Web server is returning an unknown error." It issues the code when the origin exchange ends without a usable HTTP response. For example, because the response is empty, its headers are malformed, or its status code is missing.
An origin server is the backend that hosts the site behind Cloudflare. Cloudflare receives your HTTP request first and forwards it to the origin:
With 520, the client-to-Cloudflare leg succeeds. Cloudflare reaches the origin but can't obtain or interpret a valid response. A refused origin connection points to 521, while a connection-stage timeout points to 522.
The IANA registry leaves 520 unassigned. Unlike standard codes such as 404 Not Found and 500 Internal Server Error, it has no general HTTP specification. Cloudflare uses it as a catch-all for origin-response failures its edge can't classify more precisely.
Treat 520 as a failure location, not a root-cause report. It directs you to the Cloudflare-to-origin exchange, but you still need Cloudflare logs, origin logs, and a direct origin test to identify the exact cause.
520 vs. other Cloudflare 5xx errors
Cloudflare's 5xx codes describe different failures between its edge and the origin. The exact code tells you whether to investigate connectivity, timing, TLS, or response formatting.
Error
What failed
Check first
520 Web Server Returns an Unknown Error
Cloudflare reached the origin but received an empty, malformed, or otherwise unusable response.
Application crashes, response headers, and HTTP/2 configuration.
521 Web Server Is Down
The origin refused Cloudflare's connection.
The web server process, listening port, and firewall rules.
522 Connection Timed Out
Connection setup or request acknowledgment timed out.
Origin availability, silently dropped traffic, and the network route.
524 A Timeout Occurred
The connection succeeded, but the origin didn't respond before the read timeout.
Slow application paths, server capacity, and downstream dependencies.
525 SSL Handshake Failed
TLS negotiation between Cloudflare and the origin failed.
Origin TLS settings, supported protocols, and cipher compatibility.
500 Internal Server Error or 503 Service Unavailable
A server or intermediary returned a standardized error response.
Application logs, service health, and server capacity.
Use the code as a map: 520 points to response validity, 521 to a refused connection, 522 and 524 to timeouts at different stages, and 525 to TLS. A 500 Internal Server Error differs because the server or intermediary reports a defined failure instead of leaving Cloudflare to classify an unusable exchange.
Common causes of 520 errors
The following tips are focused on site owners whose clients may be dealing with the 520 error. Most 520 errors trace to the origin returning no usable response, but the underlying failure can sit in the application, firewall, headers, or Cloudflare-to-origin protocol setup. Use the failure pattern and logs to narrow it down before changing settings.
Origin server crashes or misconfigurations
Start with origin health. An application process can accept Cloudflare's request and crash before sending a status line or response headers. PHP worker failures are a common example, but the same pattern can follow out-of-memory kills, unhandled Python errors and exceptions, failed deployments, or broken upstream dependencies.
Firewalls or security software blocking Cloudflare
Your origin firewall, security plugin, or hosting security tool can block legitimate Cloudflare traffic. At the network layer, proxied requests arrive from Cloudflare IP ranges, so a stale allowlist or aggressive rule can interrupt the exchange. A clean refusal usually produces 521, a silent timeout can produce 522, and a connection dropped after it opens can surface as 520.
Oversized response headers
Cloudflare can return 520 when origin response headers exceed 128 KB, often because Set-Cookie values accumulate or diagnostic headers grow too verbose. Some third-party guides still quote 8 KB or 32 KB, but Cloudflare's current guidance specifies 128 KB. A cookie loop can cross that limit while the HTML body remains valid, making header size easy to overlook.
Empty or malformed origin responses
Cloudflare can't forward an entirely empty response, a response without a status line, invalid header syntax, or a connection that closes before response headers arrive. The fault may sit in a reverse proxy, application server, plugin, or custom middleware rather than the main application. Check every layer that can modify the response.
Incorrect HTTP/2 configuration at the origin
Application-Layer Protocol Negotiation (ALPN) lets an origin advertise HTTP/2 during the TLS handshake. If the server accepts Cloudflare's HTTP/2 connection but fails to honor the protocol, the edge can receive an invalid exchange and return 520. Use HTTP/2 to Origin as a diagnostic: disable it temporarily, confirm whether the errors stop, and then repair the origin's HTTP/2 support.
Authenticated Origin Pull misconfiguration
Authenticated Origin Pull requires the origin to validate a client certificate presented by Cloudflare. A 520 can appear when Cloudflare enables the feature but the origin expects a different certificate, trusts the wrong certificate authority, or enforces the requirement inconsistently. Both sides must use matching certificate and trust settings.
Examples of 520 error occurrences
520 errors don't always affect every request in the same way. The following scenarios show how traffic, session state, protocol behavior, and visitor profiles can reveal the failing layer.
A PHP application crashes during a traffic spike
During a traffic spike, a PHP application exhausts its worker pool and available memory. A worker accepts Cloudflare's request, but the process dies before sending response headers. Cloudflare returns 520 for the affected requests until the process manager restarts the worker or the load subsides. The error rate rising and falling with memory pressure is the diagnostic clue.
Accumulated cookies push headers past 128 KB
A session moves through several authentication redirects, and each response adds state cookies without removing obsolete values. On the next request, the application's combined response headers cross 128 KB. Cloudflare returns 520 for that session even though a fresh browser session still works. The session-specific failure points you toward cookie and header growth.
An API route exposes an HTTP/2 mismatch
After a reverse proxy upgrade, the origin advertises HTTP/2 through ALPN but mishandles a specific API route. Normal pages continue to work, while that route returns 520 through Cloudflare. If the same request succeeds with curl --http1.1 but fails with curl --http2, you've isolated the problem to the origin's HTTP/2 path.
Only a specific visitor group receives 520
Suppose only Safari users connected through a VPN receive 520, while Chrome users and fresh sessions succeed. Don't blame Safari's TLS ClientHello: Cloudflare terminates the visitor's TLS connection at its edge. Compare cookies, HTTP headers, source networks, and region-based rules instead. A security plugin may send that request profile down a broken application path that closes before returning valid headers.
Diagnosing a 520 error
A 520 page identifies the symptom, not the cause. Diagnose it by preserving the request context, reading Cloudflare and origin logs together, and then comparing proxied and direct results.
Capture the failed request
Capture the full URL, request method, UTC timestamp, and Cloudflare Ray ID. Also note whether the error affects every visitor or only certain routes, sessions, or regions. The Ray ID ties the request to its Cloudflare edge record, while the failure scope tells you whether to investigate an origin-wide problem or a narrower request pattern.
Check Cloudflare logs
The 520 page tells you what Cloudflare served to the visitor, not what the origin returned. In Logpush's http_requests dataset, compare EdgeResponseStatus, OriginResponseStatus, and CacheStatus. EdgeResponseStatus records the client-facing code, OriginResponseStatus records the origin's code, and CacheStatus shows how Cloudflare handled the cache and origin path.
An OriginResponseStatus of 0 needs context:
- CacheStatushit or revalidated – Cloudflare served the request from cache and didn't contact the origin. The 0 is expected.
- CacheStatusmiss or expired – Cloudflare attempted an origin fetch but received no usable response. The 0 supports a genuine origin-exchange failure.
If Origin Analytics shows originResponseStatus 200 and edgeResponseStatus 520, Cloudflare received a successful status but couldn't forward the response. Check for oversized headers, invalid syntax, or an early connection close.
Review origin and intermediary logs
Match the timestamp and, when available, the Ray ID across Nginx, Apache, load balancer, firewall, and application logs. Look for worker exits, out-of-memory events, uncaught exceptions, upstream resets, malformed-header warnings, and recent deployments. A clean web server log doesn't clear the entire origin stack: a firewall or load balancer may have ended the exchange before the application recorded it.
Test the origin directly with cURL
If you control the origin, compare the proxied response with a direct request. cURL: sending headers can preserve the public hostname and TLS Server Name Indication while connecting to the origin IP:
Replace the hostname, path, and IP with your values. The first command follows public DNS through Cloudflare; the second maps the same hostname directly to the origin. If both fail, investigate the origin. If only the proxied request fails, inspect Cloudflare IP filtering, HTTP/2 to Origin, Authenticated Origin Pulls, and response compatibility.
A plain direct request isn't equivalent when Authenticated Origin Pulls protects the origin because cURL doesn't present Cloudflare's client certificate. Supply the expected certificate or test from a trusted path before interpreting that result.
Prevention and troubleshooting methods
Fix the layer your evidence identifies, then add checks that catch the same failure before visitors see it. The following steps separate immediate recovery from long-term prevention.
Immediate troubleshooting
Use the evidence from your diagnosis to change 1 layer at a time. This prevents a temporary recovery from looking like a root-cause fix.
- Allow Cloudflare traffic at the origin. Update firewalls, hosting security tools, and security plugins with Cloudflare's current IP ranges. Confirm that none of them silently drops or rate-limits Cloudflare connections.
- Stabilize the failing origin process. Restart crashed workers to restore service, then address the cause, such as memory exhaustion, unhandled exceptions, or broken upstream dependencies. Verify that the affected route returns valid headers under normal load.
- Correct protocol and authentication settings. Confirm that the origin handles HTTP/2 correctly. Temporarily disable HTTP/2 to Origin if you suspect a mismatch. If you use Authenticated Origin Pulls, verify that both sides have matching certificate and trust settings.
- Reduce response-header size. Measure the complete header block, remove obsolete cookies, and disable unnecessary diagnostic headers. Check redirect-heavy flows because they often expose uncontrolled cookie growth.
- Bypass Cloudflare briefly. Set the affected record to DNS only or pause Cloudflare, then repeat the same request. This exposes the origin to direct public traffic and bypasses Cloudflare protections, so restore proxying as soon as you capture the result.
- Escalate with complete evidence. Give Cloudflare Support the full URL, timestamp and timezone, Ray ID, /cdn-cgi/trace output, and 2 sanitized HAR files – 1 with Cloudflare enabled and 1 with it paused. Remove cookies, tokens, and form data before sharing the files.
Long-term prevention
Monitor worker exits, memory pressure, connection-pool saturation, and 5xx rates by route. Tie alerts to deployments so you can connect a new error pattern to the change that introduced it.
Keep Cloudflare IP allowlists current. Treat them as maintained infrastructure configuration, not a 1-time firewall change.
Add automated header-size checks to session and redirect flows. Catch cookie growth before response headers approach 128 KB.
Retest HTTP/2 and Authenticated Origin Pulls after web server upgrades, proxy changes, and certificate renewals. Include both direct and Cloudflare-proxied requests in those checks.
Handling 520 errors when scraping or crawling
For scraping teams, the first step is deciding whether the 520 is target-wide or specific to automation. That classification determines whether you should back off, adjust the request behavior, or test a different IP path.
Confirm whether the failure is target-wide
When your scraper receives 520, replay the exact URL in a regular browser and from another network. Then send 1 low-concurrency request from the scraper. If every path returns 520, classify it as an upstream availability problem, stop immediate retries, and schedule a later attempt. You can't repair the target's origin from the client.
If the browser succeeds but automation fails repeatedly, treat 520 as a request-pattern signal, not proof of deliberate blocking. An origin security layer may close a suspicious connection or return malformed output instead of a clean 403, which Cloudflare can surface as 520. Compare headers, cookies, timing, concurrency, and exit IPs before deciding what failed.
Correct request signals and retry behavior
Don't respond by piling on random browser headers. Send a coherent set that matches the User-Agent, including compatible Accept, Accept-Language, Accept-Encoding, and client-hint values. Keep cookie jars separate by target and session, and monitor their size. If a fresh session succeeds while a long-lived session fails, investigate cookie growth first.
Reduce per-host concurrency and retry transient 520 responses with exponential backoff and jitter. Cap retries at 3–5 attempts, and automatically retry only safe, idempotent requests. Immediate retries increase origin pressure and make automated traffic patterns more obvious.
Respond to IP-specific and anti-bot patterns
Log the status, Ray ID, route, session, exit IP, region, and retry attempt. Rotate only when 520 errors cluster around a specific address or network range. If every IP returns the same error, rotation adds cost without addressing the failure.
When errors follow a datacenter IP or range, rotating proxies can distribute requests across different addresses.Decodo's residential proxies provide rotating, ethically-sourced residential IPs for targets where residential network reputation is a better fit. Neither approach can repair an origin-wide failure.
If the target works in a regular browser but manual changes to headers, IPs, and sessions keep failing,Decodo's Site Unblocker can manage rotation, browser fingerprints, JavaScript rendering, sessions, and retries through 1 endpoint. Use it after confirming that the problem is scraper-specific. It won't fix a crashed origin or a malformed response affecting every visitor.
Final thoughts
A 520 means Cloudflare reached the origin but couldn't obtain a usable response. It tells you where the exchange failed, not why. Check OriginResponseStatus with CacheStatus, align the Ray ID and timestamp across Cloudflare and origin logs, and then compare the proxied request with a direct origin request.
Fix only the layer your evidence identifies. Site operators should correct origin health, firewall access, header growth, or protocol configuration. Scraping teams should back off target-wide failures and change request or IP behavior only when the pattern is scraper-specific. Classification beats another blind retry.
Frequently asked questions
How do I fix error code 520?
Start by comparing OriginResponseStatus with CacheStatus, then match the failed request to origin and intermediary logs. If the logs confirm an origin-exchange failure, allowlist Cloudflare IPs, fix application crashes or malformed responses, reduce headers below 128 KB, and verify HTTP/2 and Authenticated Origin Pull settings. If the error persists, pause Cloudflare briefly and escalate with the URL, timestamp, Ray ID, trace output, and sanitized HAR files.
How to fix code 520?
Check Cloudflare logs, review origin logs, and test the origin directly. Fix only the layer those checks identify, usually a firewall rule, application crash, oversized response header, or protocol mismatch.
How do I fix a Cloudflare error?
Identify the exact Cloudflare code before changing anything. A 520 indicates an unusable origin response, 521 a refused connection, 522 or 524 a timeout at different stages, and 525 a TLS handshake failure. Record the Ray ID and timestamp, then investigate the layer indicated by the code.
How do I fix error code 520 Cloudflare?
If you operate the site, compare the edge and origin status, test the origin directly, and correct the identified firewall, header, application, or protocol problem. If you're a visitor or scraper, you can't repair the origin. Capture the Ray ID, retry with backoff, and report persistent failures to the site operator.