# Fix Cloudflare 502 Bad Gateway Error
Cloudflare returns "502 Bad Gateway" when it cannot connect to your origin server or the origin server returns an invalid response.
Introduction
A 502 Bad Gateway error from Cloudflare indicates a communication problem between Cloudflare's edge servers and your origin server. Cloudflare acts as a reverse proxy, sitting between users and your server. When Cloudflare cannot establish a valid connection to your origin, it returns a 502 error to the user.
This error can occur due to several scenarios: - Origin server is down or unreachable - Origin server is overloaded and cannot respond - Firewall blocking Cloudflare IP addresses - SSL/TLS handshake failures between Cloudflare and origin - Connection timeouts due to slow responses - Invalid HTTP responses from origin server - Incorrect origin port configuration
Understanding which scenario applies to your situation is key to resolving the issue quickly.
Symptoms
When a 502 error occurs, users see:
``` 502 Bad Gateway Error code: 502
cloudflare ```
Different Cloudflare error variants:
Error 522: Connection timed out
The TCP connection to your origin server failedError 524: A timeout occurred
A timeout occurred while waiting for your origin server responseError 525: SSL handshake failed
The SSL handshake between Cloudflare and the origin server failedError 520: Web server is returning an unknown error
The origin server returned an empty, unknown, or unexpected responseIn your origin server logs, you may see: - No incoming requests (firewall blocking) - Connection drops - High load averages - SSL negotiation failures
Common Causes
- 1.Origin Server Down: Your web server (Nginx, Apache, IIS) is not running or crashed.
- 2.Firewall Blocking Cloudflare: Server firewall (iptables, ufw, security groups) blocks Cloudflare IP ranges.
- 3.SSL/TLS Configuration Mismatch: Cloudflare SSL mode incompatible with origin server certificate.
- 4.Server Overload: High CPU, memory, or connection count causing server to reject connections.
- 5.Connection Timeout: Origin server takes too long to respond (Cloudflare timeout is 100 seconds).
- 6.Wrong Origin Port: Cloudflare connecting to wrong port on origin server.
- 7.HTTP Version Mismatch: Incompatibility between Cloudflare and origin HTTP versions.
- 8.DNS Issues: DNS records pointing to wrong IP address or not propagating.
Step-by-Step Fix
Step 1: Check Origin Server Status
```bash # Test origin server directly (bypass Cloudflare) curl -I http://YOUR_ORIGIN_IP
# Or use hosts file override curl -I --resolve yourdomain.com:80:YOUR_ORIGIN_IP http://yourdomain.com
# Check if server is running ssh user@origin-server "systemctl status nginx" ssh user@origin-server "systemctl status apache2"
# Check server processes ps aux | grep nginx ps aux | grep apache ```
Step 2: Verify Firewall Allows Cloudflare
```bash # Get Cloudflare IP ranges curl https://www.cloudflare.com/ips-v4 curl https://www.cloudflare.com/ips-v6
# Allow Cloudflare IPs in ufw for ip in $(curl -s https://www.cloudflare.com/ips-v4); do ufw allow from $ip to any port 80 proto tcp ufw allow from $ip to any port 443 proto tcp done
# Allow Cloudflare IPs in iptables for ip in $(curl -s https://www.cloudflare.com/ips-v4); do iptables -A INPUT -p tcp --dport 80 -s $ip -j ACCEPT iptables -A INPUT -p tcp --dport 443 -s $ip -j ACCEPT done
# Check current firewall rules ufw status iptables -L -n ```
Step 3: Fix SSL/TLS Configuration
```bash # Check SSL certificate on origin openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
# Ensure origin server has valid certificate certbot certificates
# Check Nginx SSL configuration cat /etc/nginx/sites-enabled/default | grep ssl ```
```nginx # Nginx SSL configuration server { listen 443 ssl; server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# For Cloudflare "Full (strict)", ensure valid certificate } ```
In Cloudflare dashboard, set appropriate SSL mode: - Off: Cloudflare -> HTTP -> Origin (not secure) - Flexible: Cloudflare -> HTTP -> Origin (not secure to origin) - Full: Cloudflare -> HTTPS -> Origin (self-signed OK) - Full (strict): Cloudflare -> HTTPS -> Origin (valid cert required)
Step 4: Increase Timeouts for Slow Responses
# Increase timeout in Nginx
http {
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
}# Cloudflare timeout limits:
# Free/Pro/Business: 100 seconds max
# Enterprise: up to 600 secondsStep 5: Check Server Load and Resources
```bash # Check server load top htop
# Check memory free -h
# Check connections netstat -an | grep :80 | wc -l netstat -an | grep :443 | wc -l
# Check disk space df -h
# If overloaded, scale horizontally or increase resources ```
Step 6: Verify DNS Configuration
```bash # Check DNS resolution dig yourdomain.com nslookup yourdomain.com
# Verify DNS record in Cloudflare dashboard # Ensure record points to correct origin IP ```
Step 7: Check Cloudflare Status
```bash # Check Cloudflare status page curl -s https://www.cloudflarestatus.com/api/v2/status.json | jq
# Or visit: https://www.cloudflarestatus.com ```
Verification
After applying fixes, verify the error is resolved:
```bash # Test origin server directly curl -I http://ORIGIN_IP
# Test through Cloudflare curl -I https://yourdomain.com
# Check Cloudflare Ray ID in response headers curl -I https://yourdomain.com | grep -i ray
# Verify SSL openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
# Check DNS resolution dig yourdomain.com
# Monitor for 5 minutes watch -n 30 'curl -s -o /dev/null -w "%{http_code}\n" https://yourdomain.com' ```
Prevention
To prevent 502 errors in the future:
- 1.Monitor Origin Server Health: Set up health checks and alerts for server availability.
- 2.Allowlist Cloudflare IPs: Keep firewall rules updated with current Cloudflare IP ranges.
- 3.Use Valid SSL Certificates: Enable auto-renewal for Let's Encrypt certificates.
- 4.Implement Load Balancing: Use multiple origin servers to handle traffic spikes.
- 5.Configure Appropriate Timeouts: Match origin server timeouts with Cloudflare limits.
- 6.Monitor Server Resources: Set up alerts for CPU, memory, and connection thresholds.
- 7.Keep DNS Updated: Ensure DNS records point to correct server IPs.
- 8.Use Cloudflare Load Balancing: Enable failover to backup origins.
- 9.Enable Cloudflare Caching: Reduce origin requests through proper caching.
- 10.Document Recovery Procedures: Maintain runbook for 502 troubleshooting.
Related Articles
- [Nginx troubleshooting: Fix Lambda Permission Denied - Complete ](fix-lambda-permission-denied)
- [Nginx web server troubleshooting: Fix Client Max Body Size Large Upload Nginx Issue ](client-max-body-size-large-upload-nginx)
- [Fix Apache 502 Proxy Error](fix-apache-502-proxy-error)
- [Fix Apache LogLevel Core Debug Configuration](fix-apache-loglevel-core-debug)
- [Fix Kong Gateway 500 Error](fix-kong-gateway-500-error)
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix Cloudflare 502 Bad Gateway Error", "description": "Step-by-step guide to fix Cloudflare 502 Bad Gateway errors. Resolve origin server issues, connection problems, and configure Cloudflare proxy.", "url": "https://www.fixwikihub.com/fix-cloudflare-502-bad-gateway", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-27T10:39:00.000Z", "dateModified": "2026-04-27T10:39:00.000Z" } </script>