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:
A 504 Gateway Timeout error in Cloudflare is usually caused by one of a handful of configuration problems. Work through the causes below in order - the first ones are the most common.
Common Causes in Cloudflare
- Origin server responding too slowly
- Database queries taking too long
- An upstream proxy or load balancer behind Cloudflare timing out and returning 504 (Cloudflare's own 100-second limit shows as 524 instead)
- 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 a few minutes for the change to take effect
- Test if site works without Cloudflare
- If it works, the issue is origin server performance
- Re-enable Cloudflare (orange cloud)
Solution 4: Consider Argo Smart Routing (Paid Add-on)
- Argo Smart Routing routes traffic to your origin over less congested network paths
- It can reduce latency to the origin but does not fix a slow application
- It is a paid add-on - check current pricing in the Cloudflare dashboard before enabling it
Solution 5: Implement Application-Level Caching
- Use page caching (WordPress: WP Super Cache, W3 Total Cache)
- Implement Redis or Memcached for object caching
- Use Cloudflare Cache Rules to cache static or cacheable pages at the edge
- Set appropriate Cache-Control headers
- Cache API responses with short TTL
Prevention Tips
- Watch the Cloudflare error logs and alert on rising error rates
- Test configuration changes in a staging environment first
- Keep configuration under version control so you can roll back quickly
- Run a configuration test (e.g. nginx -t or apachectl configtest) before every reload