Cloudflare
How to Fix 504 Gateway Timeout Error with Cloudflare
Quick Fix
The most common cause of 504 errors in Cloudflare is: Origin server responding too slowly
Quick solution: For Nginx, increase timeout in /etc/nginx/sites-available/your-site:
The 504 Gateway Timeout error in Cloudflare indicates a problem specific to your Cloudflare configuration or environment. This guide provides platform-specific solutions.
Common Causes in Cloudflare
- Origin server responding too slowly
- Database queries taking too long
- Cloudflare proxy timeout (100 seconds for Free plan, 600s for Enterprise)
- Origin server overloaded
- Network connectivity issues between Cloudflare and origin
Step-by-Step Solutions
Solution 1: Increase Origin Server Timeout
- For Nginx, increase timeout in /etc/nginx/sites-available/your-site:
- fastcgi_read_timeout 300; (for PHP-FPM)
- proxy_read_timeout 300; (for reverse proxy)
- For Apache, edit httpd.conf: Timeout 300
- Reload web server: sudo systemctl reload nginx
Solution 2: Optimize Database Queries
- Enable slow query log in MySQL: slow_query_log = 1, long_query_time = 2
- Check /var/log/mysql/slow-query.log for slow queries
- Add indexes to frequently queried columns
- Use EXPLAIN to analyze query performance
- Consider query caching or Redis
Solution 3: Temporarily Bypass Cloudflare
- In Cloudflare DNS, change orange cloud to gray (DNS only)
- Wait for DNS propagation (up to 5 minutes)
- Test if site works without Cloudflare
- If it works, the issue is origin server performance
- Re-enable Cloudflare (orange cloud)
Solution 4: Enable Cloudflare Argo (Paid Feature)
- Log into Cloudflare Dashboard
- Go to Traffic → Argo
- Enable Argo Smart Routing
- This uses faster network paths to your origin
- Note: This is a paid feature ($5/month + usage)
Solution 5: Implement Application-Level Caching
- Use page caching (WordPress: WP Super Cache, W3 Total Cache)
- Implement Redis or Memcached for object caching
- Enable Cloudflare Page Rules for edge caching
- Set appropriate Cache-Control headers
- Cache API responses with short TTL
Prevention Tips
- Monitor Cloudflare error logs regularly
- Implement proper health checks and monitoring
- Keep Cloudflare and dependencies up to date
- Set up alerting for error rate increases
- Document your configuration changes
- Test configuration changes in staging first