← All guides

How to Fix 504 Gateway Timeout Error on Nginx and Apache

A 504 Gateway Timeout error occurs when a website goes down due to a communication breakdown between two servers that are not talking to each other fast enough. This failure prevents users from accessing pages because one server is waiting for a response from another server that is failing to respond quickly.

In simple terms, the 504 error means your front-end server (the “gateway,” which is often Nginx) is waiting for a response from the back-end server (where your actual code runs, like Apache or PHP-FPM). The back-end took too long to process the request, and Nginx eventually gave up.

To resolve this, we usually need to look at two specific areas: increasing the timeout limits in your configuration files so the servers have more time to “talk,” or identifying and optimizing heavy database queries that are causing the backend to hang.

Emergency Stop-Gap: If you need your site back online immediately while we dig into the permanent configuration fixes, you can force a refresh of the processes by restarting your web server services via SSH. Run these commands:

sudo systemctl restart nginx sudo systemctl restart php-fpm

This will clear out any hung processes and often restores immediate access to your site while we work on the underlying configuration issues.

Before You Start

Before you begin modifying your server configuration, we need to get your data safe by creating a full backup of both your website files and your databases. If you are using a control panel like cPanel or Plesk, export your current configuration files first. A single mistake in an Nginx or Apache configuration file can take your site offline entirely or create a security vulnerability.

Related guide: How to Clean Crypto Spam Hack Google Search Console

What are the symptoms of a 504 gateway timeout?

Seeing a 504 Gateway Timeout on your site is incredibly frustrating, especially when it means customers can’t reach your products. It feels like an immediate crisis, but it helps to understand that this specific error isn’t just a “broken” page; it’s a distinct signal regarding how your servers are communicating.

A 504 error is not the same as a standard “Page Not Found” (404) or a general server crash (500). While those errors usually mean a file is missing or a line of code has a typo, a 504 specifically indicates a communication breakdown between two servers working in tandem. To visualize this, think of your website’s infrastructure as a restaurant: Nginx acts as the “front door” and handles incoming requests from customers, while Apache or PHP-FPM acts as the “kitchen” that processes the logic to fulfill those orders. If the kitchen takes too long to cook the meal, the front door eventually gives up and tells the customer (the visitor) that there was a timeout.

You will typically recognize this issue through several specific symptoms:

  • A browser window showing a “504 Gateway Timeout” message.
  • Slow loading times followed by a sudden error page.
  • The site works for some pages but fails on heavy pages like checkout or search results.
  • Intermittent 504 errors during periods of high traffic.

Related guide: Clean Pharmaceutical Spam Links Database

Why does this error occur on Nginx and Apache servers?

When this specific error appears on your site, it usually indicates a breakdown in the “handshake” between your web server and the scripts running in the background. It is an incredibly frustrating hurdle to hit when you’re trying to keep things running smoothly, but we can narrow down exactly where that communication is failing:

  1. Inadequate Timeout Limits: The default windows for proxy_read_timeout or fastcgi_read_timeout are frequently set to 60 seconds. If your site runs a complex script—such as processing a large file, generating a heavy report, or performing a deep calculation—that takes just 61 seconds, the gateway assumes something is broken and cuts the connection entirely.
  2. Overloaded Upstream Processes: During a spike in traffic, your PHP-FPM pool can run out of available “workers” to handle incoming requests. When this happens, new visitors are placed into a waiting queue; if they sit in that line for too long because no worker is free to pick them up, the connection eventually times out.
  3. Slow Database Queries: A poorly optimized SQL query can effectively “lock” or stall a PHP process. In these cases, your script hangs while it waits for the database to finish its task and return data; because nothing is happening on the front end, Nginx loses patience and returns a 504 error.

Related guide: Elementor Gallery Broken Images: Debugging CDN & Path

How do I check the server logs for specific errors?

Think of server logs as the diagnostic report for your site’s infrastructure; they record the exact moment and reason a connection failed. When your site goes down, these files act like a flight recorder, showing us precisely where the chain broke so we can stop guessing and start fixing. To get a full picture, you need to check both the “front door” (the Nginx proxy) and the “engine room” (Apache or PHP-FPM).

For Nginx: The error log is typically located at /var/log/nginx/error.log. When reviewing this file, pay close attention to entries containing “upstream timed out” or “FastCGI sent errors.” These specific markers usually indicate that your web server tried to reach the backend, but the backend didn’t respond fast enough or crashed entirely.

For Apache/PHP-FPM: If Nginx isn’t giving you the full story, we need to look at the origin of the execution. Check /var/log/apache2/error.log or the specific PHP-FPM log, which is often located at /var/log/php-fpm.log. These will tell us if a specific plugin, theme, or script is causing a fatal error in the PHP environment.

You can monitor these logs in real-time as you refresh your site. This allows us to see the errors pop up the second they happen:

tail -f /var/log/nginx/error.log

How do I fix 504 gateway timeout errors in an Nginx config?

I’ve handled dozens of site crashes where a 504 Gateway Timeout was the only thing standing between a functioning store and a broken one. When you see this error, it generally means your Nginx server is trying to talk to your backend (like PHP or a proxy), but it’s giving up because the backend is taking too long to respond. We need to give the server more “patience” by extending these wait windows.

What are the specific Nginx directives to change?

Depending on how your site is architected, you will need to adjust the http, server, or location block. In most standard environments, these changes belong in your primary configuration file, typically located at /etc/nginx/nginx.conf.

http {
    # Increase the time Nginx waits for a response from the proxied server
    proxy_read_timeout 300;
    proxy_connect_timeout 300;
    proxy_send_timeout 300;

    # If using PHP-FPM via FastCGI, you must also update these:
    fastcgi_read_timeout 300;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
}

Once you have saved the changes to your configuration file, you need to validate the syntax and reload the service to make them live:

sudo nginx -t
sudo systemctl reload nginx

How do I adjust FastCGI timeouts for PHP-FPM?

If you are running a heavy platform like WordPress or Magento, the bottleneck might actually be happening inside the PHP layer. If the PHP process times out before Nginx even has a chance to report it, increasing the Nginx limits alone won’t fix the issue. You have to ensure that your max_execution_time in the php.ini file is equal to or greater than the values we set in Nginx.

First, locate your active configuration file:

php -i | grep "Loaded Configuration File"

Once you’ve located the path, update these specific lines:

max_execution_time = 300
memory_limit = 256M

How do I resolve the issue on the Apache side?

When Nginx handles the initial request correctly but the backend Apache server hangs because it’s struggling with a heavy task, you need to grant the system more breathing room. We do this by extending the amount of time Apache allows a script or process to run before it gives up and drops the connection.

Which specific Apache directives need adjustment?

You will need to modify your configuration files—typically found in /etc/apache2/apache.conf or within your specific virtual host file. You are looking to update the Timeout directive to ensure the server doesn’t cut off valid processes prematurely.

# Increase the time Apache spends waiting for a script to finish
Timeout 300

In cases where you are utilizing mod_proxy with your configuration, it is also necessary to update the proxy-specific timeout to keep the connection stable:

ProxyTimeout 300

Once you have saved these changes to your configuration files, you must restart the Apache service for the new limits to take effect. Run the following command in your terminal:

sudo systemctl restart apache2

Is a slow database query causing the timeout?

Your site might be perfectly healthy on the surface, but a bottleneck in your database can cause everything to grind to a halt. It is incredibly common for the issue to lie not within your Nginx configuration, but with a “heavy” query deep in the backend. If a specific plugin or an unoptimized table causes a request to hang for 30 seconds, it provides more than enough time for the server to give up and trigger a 504 Gateway Timeout error.

We need to identify exactly where these delays are occurring. To isolate these culprits in MySQL or MariaDB, you should enable the slow query log. This will highlight exactly which processes are dragging your site down:

SET GLOBAL slow_query_log = '1';
SET GLOBAL long_query_time = 2;

By setting the threshold to 2 seconds, the system will begin logging any query that takes longer than that window. Once you have this running, you can analyze the logs to pinpoint whether a specific table requires better indexing or if a particular plugin is malfunctioning and causing the hang. This moves us from guessing where the problem is to seeing exactly which piece of code needs fixing.

Audit Summary Table

I know how unsettling it feels when your website starts throwing errors or hanging during critical moments. It feels like the foundation is crumbling, but these specific issues are actually common “under-the-hood” bottlenecks that occur as site traffic grows or complex scripts run. We can stabilize this by tightening up your server configuration and optimizing how your database handles requests.

Here is the breakdown of the technical hurdles we need to address to get your site running smoothly again:

Issue CategoryTechnical ActionsBusiness Value
Proxy TimeoutIncrease proxy_read_timeout in Nginx configPrevents 504 errors on long-running scripts (e.g., exports)
FastCGI TimeoutIncrease fastcgi_read_timeout & PHP max_execution_timeEnsures complex PHP tasks finish before the gateway drops them
Database BottleneckIdentify and index slow queries via slow_query_logImproves overall site speed and reduces server load
Process ExhaustionIncrease pm.max_children in PHP-FPM poolAllows the server to handle more concurrent visitors during spikes

What common mistakes make this problem worse?

  1. Inconsistent Timeouts: This is a common trap where Nginx and PHP aren’t in sync. If you set Nginx to 300 seconds but leave your PHP configuration at 60, the “inner” process—the one actually running your code—will die first. Because that connection was severed prematurely by the internal limit, Nginx will still report a 504 or 502 error because it can no longer communicate with the backend.
  2. Restarting instead of Fixing: It’s tempting to just restart the server (the “reboot loop”) when things get sluggish. While restarting clears the symptoms by killing hung processes, it doesn’t address the root cause, such as a slow database query or an insufficient timeout limit. You are clearing the smoke from the engine, but you aren’t fixing the mechanical failure that caused the fire in the first place.
  3. Ignoring max_children: Even if your Nginx configuration is perfect, it won’t help if your PHP-FPM pool is too small. If there are no available workers to pick up incoming requests, the system literally has no “hands” to do the work. The request will fail because the process queue is full, regardless of how long you tell Nginx to wait.

When should I call a professional?

There are moments when a technical hurdle is too deep for standard troubleshooting and requires an expert with specialized access. You should reach out to a server administrator or a dedicated site recovery specialist if you encounter any of the following:

  • Persistent 504 errors: If your 504 Gateway Timeout errors remain after you have increased all timeout values to 300 seconds, it indicates an infrastructure-level issue that is beyond simple configuration tweaks.
  • Runaway scripts: If your server’s CPU usage stays pinned at 100% even when traffic is low, you likely have a “runaway” script—a process stuck in a loop that requires a specialist to identify and terminate the specific code causing the spike.
  • Loss of access: If you cannot access your configuration files via SSH or through your primary control panel, you need an administrator to restore your permissions before any further troubleshooting can take place.
  • Complex logical failures: If errors only trigger on specific pages, it often points toward deep-seated database corruption or complex plugin conflicts that require a manual code audit rather than standard fixes.

Frequently Asked Questions

Why does my site show a 504 error even though the server is "online"?

It is incredibly frustrating to see your website go down when your dashboard indicates that the hardware is still powered on and running. A 504 error specifically means that while the physical server is active, the internal software "handshake" failed because it took too long. In most cases, this is a communication breakdown between the front-end web server (like Nginx or Apache) and the back-end processor (usually PHP). The front end was waiting for the back end to finish its task, but the countdown clock ran out before the data was delivered.

How do I check if my PHP-FPM pool is full?

If you suspect that your server is struggling to handle the volume of incoming requests, checking the status of your PHP-FPM process pool is a logical next step. You can see how many "workers" are currently active using a command like: ```bash pmlist | grep "php-fpm" ``` (Depending on your specific operating system and version, you might need to use `systemctl status php7.4-fpm`). If the number of active children hits your `max_children` limit, it means every available worker is occupied, and new requests are being dropped. To fix this, you will need to increase that limit within your pool configuration file, typically located at `/etc/php/X.X/fpm/pool.d/www.conf`.

Can a firewall cause a 504 Gateway Timeout?

Usually, a firewall acts as a wall; if it blocks traffic, you will see a "Connection Timed Out" or "Connection Refused" error instead of a 504. However, there is a specific scenario involving proxy services like Cloudflare. Because these services sit between your visitor and your server, they may report a 504 if your server takes too long to respond—even by just a second beyond the allowed limit. If you use a service like Cloudflare, I recommend checking their official status page first to determine if the bottleneck is within their network before you spend time troubleshooting your local firewall rules.

Is there a difference between a 502 and a 504 error?

Yes, and identifying which one you are seeing helps pinpoint exactly where the "break" in the chain is happening. A 502 Bad Gateway indicates that the upstream server sent back an invalid or broken response—think of it as the kitchen sending out a plate with no food on it. A 504 Gateway Timeout means the upstream server took too long to respond at all; in this case, the "kitchen" never even got around to sending anything because the timer ran out first.

Need this fixed right now?

We dig into server logs and fix the root cause, not the symptom. See our 500 & Server Error Repair service — repairs start from $149.

Fix My Site Now