Ошибка 504 cloudflare

Error analytics

Error Analytics per domain are available within Zone Analytics. Error Analytics allows insight into overall errors by HTTP error code and provides the URLs, source IP addresses, and Cloudflare data centers needed to diagnose and resolve the issue.  Error Analytics are based on a 1% traffic sample.

To view Error Analytics:

  • Log in to the Cloudflare dashboard.
  • Click the appropriate Cloudflare account for your site, then pick the domain.
  • Next, click the Analytics & Logs app icon.
  • Click Add filter, select Edge status code or Origin status code and choose any 5xx error code that you want to diagnose.

Error 500: internal server error

Error 500 generally indicates an issue with your origin web server.  Error establishing database connection is a common HTTP 500 error message generated by your origin web server.  Contact your hosting provider to resolve.

Resolution

Provide details to your hosting provider to assist troubleshooting the issue.

However, if the 500 error contains “cloudflare” or “cloudflare-nginx” in the HTML response body, provide 
Cloudflare support with the following information:

  1. Your domain name
  2. The time and timezone of the 500 error occurrence
  3. The output of www.example.com/cdn-cgi/trace from the browser where the 500 error was observed (replace www.example.com with your actual domain and host name)

Error 502 bad gateway or error 504 gateway timeout

An HTTP 502 or 504 error occurs when Cloudflare is unable to establish contact with your origin web server.

There are two possible causes:

  • (Most common cause) 502/504 from your origin web server
  • 502/504 from Cloudflare

502/504 from your origin web server

Cloudflare returns an Cloudflare-branded HTTP 502 or 504 error when your origin web server responds with a standard HTTP 502 bad gateway or 504 gateway timeout error:

Example of a Cloudflare-branded error 502.

Resolution

Contact your hosting provider to troubleshoot these common causes at your origin web server:

  • Ensure the origin server responds to requests for the hostname and domain within the visitor’s URL that generated the 502 or 504 error.
  • Investigate excessive server loads, crashes, or network failures.
  • Identify applications or services that timed out or were blocked.

502/504 from Cloudflare

A 502 or 504 error originating from Cloudflare appears as follows:

Example of an unbranded error 502.

If the error does not mention “cloudflare,” contact your hosting provider for assistance on 502/504 errors from your origin.

Resolution

To avoid delays processing your inquiry, provide these required details to 
Cloudflare Support:

  1. Time and timezone the issue occurred.
  2. URL that resulted in the HTTP 502 or 504 response (for example: 
    https://www.example.com/images/icons/image1.png
    )
  3. Output from browsing to 
    www.example.com/cdn-cgi/trace
     (replace 
    www.example.com
     with the domain and host name that caused the HTTP 502 or 504 error)

Error 503: service temporarily unavailable

HTTP error 503 occurs when your origin web server is overloaded. There are two possible causes discernible by error message:

  • Error doesn’t contain “cloudflare” or “cloudflare-nginx” in the HTML response body.

Resolution: Contact your hosting provider to verify if they rate limit requests to your origin web server.

  • Error contains “cloudflare” or “cloudflare-nginx” in the HTML response body.

Resolution: A connectivity issue occured in a Cloudflare data center. Provide 
Cloudflare support with the following information:

  1. Your domain name
  2. The time and timezone of the 503 error occurrence
  3. The output of 
    www.example.com/cdn-cgi/trace
     from the browser where the 503 error was observed (replace 
    www.example.com
     with your actual domain and host name)

Error 520: web server returns an unknown error

Error 520 occurs when the origin server returns an empty, unknown, or unexpected response to Cloudflare.

Resolution

Contact your hosting provider or site administrator and request a review of your origin web server error logs for crashes and to check for these common causes:

  • Origin web server application crashes
  • Cloudflare IPs not allowed at your origin
  • Headers exceeding 16 KB (typically due to too many cookies)
  • An empty response from the origin web server that lacks an HTTP status code or response body
  • Missing response headers or origin web server not returning 
    proper HTTP error responses.

    • upstream prematurely closed connection while reading response header from upstream is a common error we may notice in our logs. This indicates the origin web server was having issues which caused Cloudflare to generate 520 errors.

If 520 errors continue after contacting your hosting provider or site administrator, provide the following information to 
Cloudflare Support:

  • Full URL(s) of the resource requested when the error occurred
  • Cloudflare cf-ray from the 520 error message
  • Output from 
    http://www.example.com/cdn-cgi/trace
     (replace 
    www.example.com
     with your hostname and domain where the 520 error occurred)
  • Two 
    HAR files:

    • one with Cloudflare enabled on your website, and
    • the other with 
      Cloudflare temporarily disabled.

Error 521: web server is down

Error 521 occurs when the origin web server refuses connections from Cloudflare. Security solutions at your origin may block legitimate connections from certain 
Cloudflare IP addresses.

The two most common causes of 521 errors are:

  • Offlined origin web server application
  • Blocked Cloudflare requests

Resolution

Contact your site administrator or hosting provider to eliminate these common causes:

  • Ensure your origin web server is responsive
  • Review origin web server error logs to identify web server application crashes or outages.
  • Confirm 
    Cloudflare IP addresses are not blocked or rate limited
  • Allow all 
    Cloudflare IP ranges in your origin web server’s firewall or other security software
  • Confirm that — if you have your SSL/TLS mode set to Full or Full (Strict) — you have installed a Cloudflare Origin Certificate
  • Find additional troubleshooting information on the 
    Cloudflare Community.

Error 522: connection timed out

Error 522 occurs when Cloudflare times out contacting the origin web server. Two different timeouts cause HTTP error 522 depending on when they occur between Cloudflare and the origin web server:

  1. Before a connection is established, the origin web server does not return a SYN+ACK to Cloudflare within 15 seconds of Cloudflare sending a SYN.
  2. After a connection is established, the origin web server doesn’t acknowledge (ACK) Cloudflare’s resource request within 90 seconds.

Resolution

Contact your hosting provider to check the following common causes at your origin web server:

  • (Most common cause) 
    Cloudflare IP addresses are rate limited or blocked in .htaccess, iptables, or firewalls. Confirm your hosting provider allows Cloudflare IP addresses.
  • An overloaded or offline origin web server drops incoming requests.
  • Keepalives are disabled at the origin web server.
  • The origin IP address in your Cloudflare DNS app does not match the IP address currently provisioned to your origin web server by your hosting provider.
  • Packets were dropped at your origin web server.

If you are using Cloudflare Pages, verify that you have a custom domain set up and that your CNAME record is pointed to your custom Pages domain. Instructions on how to set up a custom Pages domain can be found here.

If none of the above leads to a resolution, request the following information from your hosting provider or site administrator before 
contacting Cloudflare support:

  • An 
    MTR or traceroute from your origin web server to a 
    Cloudflare IP address that most commonly connected to your origin web server before the issue occurred. Identify a connecting Cloudflare IP recorded in the origin web server logs.
  • Details from the hosting provider’s investigation such as pertinent logs or conversations with the hosting provider.

Error 523: origin is unreachable

Error 523 occurs when Cloudflare cannot contact your origin web server. This typically occurs when a network device between Cloudflare and the origin web server doesn’t have a route to the origin’s IP address.

Resolution Contact your hosting provider to exclude the following common causes at your origin web server:

  • Confirm the correct origin IP address is listed for A or AAAA records within your Cloudflare DNS app.
  • Troubleshoot Internet routing issues between your origin and Cloudflare, or with the origin itself.

If none of the above leads to a resolution, request the following information from your hosting provider or site administrator:

  • An 
    MTR or traceroute from your origin web server to a 
    Cloudflare IP address that most commonly connected to your origin web server before the issue occurred. Identify a connecting Cloudflare IP from the logs of the origin web server.
  • If you use Railgun (deprecated) via a Cloudflare Hosting Partner, contact your hosting provider to troubleshoot the 523 errors.
  • If you manage your Railgun (deprecated) installation, provide the following:

    • traceroute to your origin web server from your Railgun server.
    • The most recent syslog file from your Railgun server.

Error 524: a timeout occurred

Error 524 indicates that Cloudflare successfully connected to the origin web server, but the origin did not provide an HTTP response before the default 100 second connection timed out. This can happen if the origin server is simply taking too long because it has too much work to do — e.g. a large data query, or because the server is struggling for resources and cannot return any data in time.

Resolution

Here are the options we’d suggest to work around this issue:

  • Implement status polling of large HTTP processes to avoid hitting this error.
  • Contact your hosting provider to exclude the following common causes at your origin web server:
    • A long-running process on the origin web server.
    • An overloaded origin web server.
  • Enterprise customers can increase the 524 timeout up to 6000 seconds using the proxy_read_timeout API endpoint.
  • If you regularly run HTTP requests that take over 100 seconds to complete (for example large data exports), move those processes behind a subdomain not proxied (grey clouded) in the Cloudflare DNS app.
  • If error 524 occurs for a domain using Cloudflare Railgun (deprecated), ensure the lan.timeout is set higher than the default of 30 seconds and restart the railgun service.

Error 525: SSL handshake failed

525 errors indicate that the SSL handshake between Cloudflare and the origin web server failed. Error 525 occurs when these two conditions are true:

  1. The 
    SSL handshake fails between Cloudflare and the origin web server, and
  2. Full or Full (Strict) SSL is set in the Overview tab of your Cloudflare SSL/TLS app.

Resolution

Contact your hosting provider to exclude the following common causes at your origin web server:

  • No valid SSL certificate installed
  • Port 443 (or other custom secure port) is not open
  • No 
    SNI support
  • The cipher suites accepted by Cloudflare does not match the cipher suites supported by the origin web server

Additional checks

  • Check if you have a certificate installed on your origin server. You can check this article for more details on how to run some tests. In case you don’t have any certificate, you can create and install our free Cloudflare origin CA certificate. Using Origin CA certificates allows you to encrypt traffic between Cloudflare and your origin web server.
  • Review the cipher suites your server is using to ensure they match what is supported by Cloudflare.
  • Check your server’s error logs from the timestamps you see 525s to ensure there are errors that could be causing the connection to be reset during the SSL handshake.

Error 526: invalid SSL certificate

Error 526 occurs when these two conditions are true:

  1. Cloudflare cannot validate the SSL certificate at your origin web server, and
  2. Full SSL (Strict) SSL is set in the Overview tab of your Cloudflare SSL/TLS app.

Resolution

Request your server administrator or hosting provider to review the origin web server’s SSL certificates and verify that:

  • Certificate is not expired
  • Certificate is not revoked
  • Certificate is signed by a 
    Certificate Authority (not self-signed)
  • The requested or target domain name and hostname are in the certificate’s Common Name or Subject Alternative Name
  • Your origin web server accepts connections over port SSL port 443
  • Temporarily pause Cloudflare and visit 
    https://www.sslshopper.com/ssl-checker.html#hostname=www.example.com (replace www.example.com with your hostname and domain) to verify no issues exists with the origin SSL certificate:

Screen showing an SSL certificate with no errors.

If the origin server uses a self-signed certificate, configure the domain to use Full SSL instead of Full SSL (Strict). Refer to recommended SSL settings for your origin.


527 Error: Railgun Listener to origin error

A 527 error indicates an interrupted connection between Cloudflare and your origin’s 
Railgun server (rg-listener). Common causes include:

  • Firewall interference
  • Network incidents or packet loss between the Railgun server and Cloudflare

Common causes of 527 errors include:

  • Connection timeouts
  • LAN timeout exceeded
  • Connection refusals
  • TLS/SSL related errors

If contacting Cloudflare support, provide the following information from the Railgun Listener:

  • The full content of the railgun.conf file
  • The full content of the railgun-nat.conf file
  • Railgun log files that detail the observed errors

Connection timeouts

The following Railgun log errors indicate a connection failure between the Railgun Listener and your origin web server:

connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443: i/o timeout

no response from origin (timeout) 0.0.0.0:80/example.com

Resolution

Contact your hosting provider for assistance to test for connectivity issues between your origin web server and your Railgun Listener. For example, a netcat command tests connectivity when run from the Railgun Listener to the origin web server’s SERVERIP and PORT (80 for HTTP or 443 for HTTPS):

LAN timeout exceeded

The following Railgun Listener log error is generated if the origin web server does not send an HTTP response to the Railgun Listener within the 30 second default timeout:

connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443: i/o timeout

The time is adjusted by the lan.timeout parameter of the railgun.conf file.

Resolution

Either increase the lan.timeout limit in railgun.conf, or review the web server configuration. Contact your hosting provider to confirm if the origin web server is overloaded.

Connection refusals

The following errors appear in the Railgun logs when requests from the Railgun Listener are refused:

Error getting page: dial tcp 0.0.0.0:80:connection refused

Resolution

Allow the IP of your Railgun Listener at your origin web server’s firewall.

The following errors appear in the Railgun logs if TLS connections fail:

connection failed 0.0.0.0:443/example.com: remote error: handshake failure

connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443:connection refused

connection failed 127.0.0.1:443/www.example.com: x509: certificate is valid for

example.com, not www.example.com

Resolution

If TLS/SSL errors occur, check the following on the origin web server and ensure that:

  • Port 443 is open
  • An SSL certificate is presented by the origin web server
  • the SAN or Common Name of the origin web server’s SSL certificate contains the requested or target hostname
  • SSL is set to Full or Full (Strict) in the Overview tab of the Cloudflare SSL/TLS app

Error 530

HTTP error 530 is returned with an accompanying 1XXX error displayed. Search for the specific 
1XXX error within the Cloudflare Help Center for troubleshooting information.


  • Gathering information to troubleshoot site issues
  • Contacting Cloudflare Support
  • Customizing Cloudflare error pages
  • MTR/Traceroute Diagnosis and Usage
  • Cloudflare Community Tips
pcx_content_type title source

troubleshooting

Troubleshooting Cloudflare 5XX errors

Troubleshooting Cloudflare 5XX errors – Cloudflare Help Center

Error analytics

Error Analytics per domain are available within Zone Analytics. Error Analytics allows insight into overall errors by HTTP error code and provides the URLs, source IP addresses, and Cloudflare data centers needed to diagnose and resolve the issue.  Error Analytics are based on a 1% traffic sample.

To view Error Analytics:

  • Log in to the Cloudflare dashboard.
  • Click the appropriate Cloudflare account for your site, then pick the domain.
  • Next, click the Analytics & Logs app icon.
  • Click Add filter, select Edge status code or Origin status code and choose any 5xx error code that you want to diagnose.

Error 500: internal server error

Error 500 generally indicates an issue with your origin web server.  Error establishing database connection is a common HTTP 500 error message generated by your origin web server.  Contact your hosting provider to resolve.

Resolution

Provide details to your hosting provider to assist troubleshooting the issue.

However, if the 500 error contains “cloudflare” or “cloudflare-nginx” in the HTML response body, provide Cloudflare support with the following information:

  1. Your domain name
  2. The time and timezone of the 500 error occurrence
  3. The output of www.example.com/cdn-cgi/trace from the browser where the 500 error was observed (replace www.example.com with your actual domain and host name)

{{

}}
If you observe blank or white pages when visiting your website, confirm
whether the issue occurs when temporarily pausing
Cloudflare
and contact your hosting provider for assistance.
{{}}


Error 502 bad gateway or error 504 gateway timeout

An HTTP 502 or 504 error occurs when Cloudflare is unable to establish contact with your origin web server.

There are two possible causes:

  • (Most common cause) 502/504 from your origin web server
  • 502/504 from Cloudflare

502/504 from your origin web server

Cloudflare returns an Cloudflare-branded HTTP 502 or 504 error when your origin web server responds with a standard HTTP 502 bad gateway or 504 gateway timeout error:

Example of a Cloudflare-branded error 502.

Resolution

Contact your hosting provider to troubleshoot these common causes at your origin web server:

  • Ensure the origin server responds to requests for the hostname and domain within the visitor’s URL that generated the 502 or 504 error.
  • Investigate excessive server loads, crashes, or network failures.
  • Identify applications or services that timed out or were blocked.

502/504 from Cloudflare

A 502 or 504 error originating from Cloudflare appears as follows:

Example of an unbranded error 502.

If the error does not mention “cloudflare,” contact your hosting provider for assistance on 502/504 errors from your origin.

Resolution

To avoid delays processing your inquiry, provide these required details to Cloudflare Support:

  1. Time and timezone the issue occurred.
  2. URL that resulted in the HTTP 502 or 504 response (for example: https://www.example.com/images/icons/image1.png)
  3. Output from browsing to _www.example.com/cdn-cgi/trace_ (replace _www.example.com_ with the domain and host name that caused the HTTP 502 or 504 error)

Error 503: service temporarily unavailable

HTTP error 503 occurs when your origin web server is overloaded. There are two possible causes discernible by error message:

  • Error doesn’t contain “cloudflare” or “cloudflare-nginx” in the HTML response body.

Resolution: Contact your hosting provider to verify if they rate limit requests to your origin web server.

  • Error contains “cloudflare” or “cloudflare-nginx” in the HTML response body.

Resolution: A connectivity issue occured in a Cloudflare data center. Provide Cloudflare support with the following information:

  1. Your domain name
  2. The time and timezone of the 503 error occurrence
  3. The output of _www.example.com/cdn-cgi/trace_ from the browser where the 503 error was observed (replace www.example.com with your actual domain and host name)

Error 520: web server returns an unknown error

Error 520 occurs when the origin server returns an empty, unknown, or unexpected response to Cloudflare.

Resolution

{{

}}
A quick workaround while further investigating 520 errors is to either
make the record
DNS-only
in the Cloudflare DNS app or temporarily pause
Cloudflare.
{{}}

Contact your hosting provider or site administrator and request a review of your origin web server error logs for crashes and to check for these common causes:

  • Origin web server application crashes
  • Cloudflare IPs not allowed at your origin
  • Headers exceeding 16 KB (typically due to too many cookies)
  • An empty response from the origin web server that lacks an HTTP status code or response body
  • Missing response headers or origin web server not returning proper HTTP error responses.
    • upstream prematurely closed connection while reading response header from upstream is a common error we may notice in our logs. This indicates the origin web server was having issues which caused Cloudflare to generate 520 errors.

{{

}}
520 errors are prevalent with certain PHP applications that crash the
origin web server.
{{}}

If 520 errors continue after contacting your hosting provider or site administrator, provide the following information to Cloudflare Support:

  • Full URL(s) of the resource requested when the error occurred
  • Cloudflare cf-ray from the 520 error message
  • Output from _http://www.example.com/cdn-cgi/trace_ (replace _www.example.com_ with your hostname and domain where the 520 error occurred)
  • Two HAR files:
    • one with Cloudflare enabled on your website, and
    • the other with Cloudflare temporarily disabled.

Error 521: web server is down

Error 521 occurs when the origin web server refuses connections from Cloudflare. Security solutions at your origin may block legitimate connections from certain Cloudflare IP addresses.

The two most common causes of 521 errors are:

  • Offlined origin web server application
  • Blocked Cloudflare requests

Resolution

Contact your site administrator or hosting provider to eliminate these common causes:

  • Ensure your origin web server is responsive
  • Review origin web server error logs to identify web server application crashes or outages.
  • Confirm Cloudflare IP addresses are not blocked or rate limited
  • Allow all Cloudflare IP ranges in your origin web server’s firewall or other security software
  • Confirm that — if you have your SSL/TLS mode set to Full or Full (Strict) — you have installed a Cloudflare Origin Certificate
  • Find additional troubleshooting information on the Cloudflare Community.

Error 522: connection timed out

Error 522 occurs when Cloudflare times out contacting the origin web server. Two different timeouts cause HTTP error 522 depending on when they occur between Cloudflare and the origin web server:

  1. Before a connection is established, the origin web server does not return a SYN+ACK to Cloudflare within 15 seconds of Cloudflare sending a SYN.
  2. After a connection is established, the origin web server doesn’t acknowledge (ACK) Cloudflare’s resource request within 90 seconds.

Resolution

Contact your hosting provider to check the following common causes at your origin web server:

  • (Most common cause) Cloudflare IP addresses are rate limited or blocked in .htaccess, iptables, or firewalls. Confirm your hosting provider allows Cloudflare IP addresses.
  • An overloaded or offline origin web server drops incoming requests.
  • Keepalives are disabled at the origin web server.
  • The origin IP address in your Cloudflare DNS app does not match the IP address currently provisioned to your origin web server by your hosting provider.
  • Packets were dropped at your origin web server.

If you are using Cloudflare Pages, verify that you have a custom domain set up and that your CNAME record is pointed to your custom Pages domain. Instructions on how to set up a custom Pages domain can be found here.

If none of the above leads to a resolution, request the following information from your hosting provider or site administrator before contacting Cloudflare support:

  • An MTR or traceroute from your origin web server to a Cloudflare IP address that most commonly connected to your origin web server before the issue occurred. Identify a connecting Cloudflare IP recorded in the origin web server logs.
  • Details from the hosting provider’s investigation such as pertinent logs or conversations with the hosting provider.

Error 523: origin is unreachable

Error 523 occurs when Cloudflare cannot contact your origin web server. This typically occurs when a network device between Cloudflare and the origin web server doesn’t have a route to the origin’s IP address.

Resolution Contact your hosting provider to exclude the following common causes at your origin web server:

  • Confirm the correct origin IP address is listed for A or AAAA records within your Cloudflare DNS app.
  • Troubleshoot Internet routing issues between your origin and Cloudflare, or with the origin itself.

If none of the above leads to a resolution, request the following information from your hosting provider or site administrator:

  • An MTR or traceroute from your origin web server to a Cloudflare IP address that most commonly connected to your origin web server before the issue occurred. Identify a connecting Cloudflare IP from the logs of the origin web server.
  • If you use Railgun (deprecated) via a Cloudflare Hosting Partner, contact your hosting provider to troubleshoot the 523 errors.
  • If you manage your Railgun (deprecated) installation, provide the following:
    • A traceroute to your origin web server from your Railgun server.
    • The most recent syslog file from your Railgun server.

Error 524: a timeout occurred

Error 524 indicates that Cloudflare successfully connected to the origin web server, but the origin did not provide an HTTP response before the default 100 second connection timed out. This can happen if the origin server is simply taking too long because it has too much work to do — e.g. a large data query, or because the server is struggling for resources and cannot return any data in time.

{{

}}
A 522 occurs if the origin web server
acknowledges (ACK) the resource request after the connection has been
established, but does not send a timely response.
{{}}

Resolution

Here are the options we’d suggest to work around this issue:

  • Implement status polling of large HTTP processes to avoid hitting this error.
  • Contact your hosting provider to exclude the following common causes at your origin web server:
    • A long-running process on the origin web server.
    • An overloaded origin web server.

{{

}}
Logging request response time at your origin web server helps identify
the cause of resource slowness. Contact your hosting provider or site
administrator for assistance in adjusting log formats or search for
related logging documentation for your brand of web server such as
Apache
or
Nginx.
{{}}

  • Enterprise customers can increase the 524 timeout up to 6000 seconds using the proxy_read_timeout API endpoint.
  • If you regularly run HTTP requests that take over 100 seconds to complete (for example large data exports), move those processes behind a subdomain not proxied (grey clouded) in the Cloudflare DNS app.
  • If error 524 occurs for a domain using Cloudflare Railgun (deprecated), ensure the lan.timeout is set higher than the default of 30 seconds and restart the railgun service.

Error 525: SSL handshake failed

525 errors indicate that the SSL handshake between Cloudflare and the origin web server failed. Error 525 occurs when these two conditions are true:

  1. The SSL handshake fails between Cloudflare and the origin web server, and
  2. Full or Full (Strict) SSL is set in the Overview tab of your Cloudflare SSL/TLS app.

{{

}}
If your hosting provider frequently changes your origin web server’s IP
address, refer to Cloudflare’s documentation on dynamic DNS
updates.
{{}}

Resolution

Contact your hosting provider to exclude the following common causes at your origin web server:

  • No valid SSL certificate installed
  • Port 443 (or other custom secure port) is not open
  • No SNI support
  • The cipher suites accepted by Cloudflare does not match the cipher suites supported by the origin web server

{{

}}
If 525 errors occur intermittently, review the origin web server error
logs to determine the cause. Configure Apache to log mod_ssl
errors.
Also, nginx includes SSL errors in its standard error log, but may
possibly require an increased log
level.
{{}}

Additional checks

  • Check if you have a certificate installed on your origin server. You can check this article for more details on how to run some tests. In case you don’t have any certificate, you can create and install our free Cloudflare origin CA certificate. Using Origin CA certificates allows you to encrypt traffic between Cloudflare and your origin web server.
  • Review the cipher suites your server is using to ensure they match what is supported by Cloudflare.
  • Check your server’s error logs from the timestamps you see 525s to ensure there are errors that could be causing the connection to be reset during the SSL handshake.

Error 526: invalid SSL certificate

Error 526 occurs when these two conditions are true:

  1. Cloudflare cannot validate the SSL certificate at your origin web server, and
  2. Full SSL (Strict) SSL is set in the Overview tab of your Cloudflare SSL/TLS app.

Resolution

{{

}}
For a potential quick fix, set SSL to Full instead of Full
(strict)
in the Overview tab of your Cloudflare SSL/TLS app for
the domain.
{{}}

Request your server administrator or hosting provider to review the origin web server’s SSL certificates and verify that:

  • Certificate is not expired
  • Certificate is not revoked
  • Certificate is signed by a Certificate Authority (not self-signed)
  • The requested or target domain name and hostname are in the certificate’s Common Name or Subject Alternative Name
  • Your origin web server accepts connections over port SSL port 443
  • Temporarily pause Cloudflare and visit https://www.sslshopper.com/ssl-checker.html#hostname=www.example.com (replace www.example.com with your hostname and domain) to verify no issues exists with the origin SSL certificate:

Screen showing an SSL certificate with no errors.

If the origin server uses a self-signed certificate, configure the domain to use Full SSL instead of Full SSL (Strict). Refer to recommended SSL settings for your origin.


527 Error: Railgun Listener to origin error

{{}}

A 527 error indicates an interrupted connection between Cloudflare and your origin’s Railgun server (rg-listener). Common causes include:

  • Firewall interference
  • Network incidents or packet loss between the Railgun server and Cloudflare

{{

}}
For additional details to aid troubleshooting, increase Railgun
logging.
{{}}

Common causes of 527 errors include:

  • Connection timeouts
  • LAN timeout exceeded
  • Connection refusals
  • TLS/SSL related errors

If contacting Cloudflare support, provide the following information from the Railgun Listener:

  • The full content of the railgun.conf file
  • The full content of the railgun-nat.conf file
  • Railgun log files that detail the observed errors

Connection timeouts

The following Railgun log errors indicate a connection failure between the Railgun Listener and your origin web server:

connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443: i/o timeout
no response from origin (timeout) 0.0.0.0:80/example.com

Resolution

Contact your hosting provider for assistance to test for connectivity issues between your origin web server and your Railgun Listener. For example, a netcat command tests connectivity when run from the Railgun Listener to the origin web server’s SERVERIP and PORT (80 for HTTP or 443 for HTTPS):

LAN timeout exceeded

The following Railgun Listener log error is generated if the origin web server does not send an HTTP response to the Railgun Listener within the 30 second default timeout:

connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443: i/o timeout

The time is adjusted by the lan.timeout parameter of the railgun.conf file.

Resolution

Either increase the lan.timeout limit in railgun.conf, or review the web server configuration. Contact your hosting provider to confirm if the origin web server is overloaded.

Connection refusals

The following errors appear in the Railgun logs when requests from the Railgun Listener are refused:

Error getting page: dial tcp 0.0.0.0:80:connection refused

Resolution

Allow the IP of your Railgun Listener at your origin web server’s firewall.

TLS/SSL related errors

The following errors appear in the Railgun logs if TLS connections fail:

connection failed 0.0.0.0:443/example.com: remote error: handshake failure
connection failed 0.0.0.0:443/example.com: dial tcp 0.0.0.0:443:connection refused
connection failed 127.0.0.1:443/www.example.com: x509: certificate is valid for
example.com, not www.example.com

Resolution

If TLS/SSL errors occur, check the following on the origin web server and ensure that:

  • Port 443 is open
  • An SSL certificate is presented by the origin web server
  • the SAN or Common Name of the origin web server’s SSL certificate contains the requested or target hostname
  • SSL is set to Full or Full (Strict) in the Overview tab of the Cloudflare SSL/TLS app

{{

}}
If your origin web server SSL certificate is self-signed, set
validate.cert=0 in
railgun.conf.
{{}}


Error 530

HTTP error 530 is returned with an accompanying 1XXX error displayed. Search for the specific 1XXX error within the Cloudflare Help Center for troubleshooting information.


Related resources

  • Gathering information to troubleshoot site issues
  • Contacting Cloudflare Support
  • Customizing Cloudflare error pages
  • MTR/Traceroute Diagnosis and Usage
  • Cloudflare Community Tips

Stuck with Cloudflare error 504? We can help you.

Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.

This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.

It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.

Here at Bobcares, we often fix this error for our customers as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix this Cloudflare error for our customers.

What causes error 504 gateway timeout?

Some of the main causes for the Cloudflare 504 gateway timeout error is given below:

1. Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.

cloudflare error 504

2. 504 error originating from Cloudflare end.

cloudflare error 504

3. The 504 gateway timeout error at Cloudflare due to large uploads

How to fix Cloudflare error 504 gateway timeout

We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.

1. Fix for Receiving 504 from the origin web server 

We will ensure the below aspects at the webserver:

1. First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.

2. Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.

3. High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.

4.  Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.

2. Fix for 504 error originating from Cloudflare

At times error 504 will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.

However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.

For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:

1. The exact time and timezone when the issue occurred
2. URL that resulted in the HTTP 504 error as a response.

3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads

The reason for this is the size of the uploads to the site being too large causing server timeouts.

Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.

This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.

[Still, facing error? We are happy to help you!]

Conclusion

To conclude, we saw some of the common causes for the 504 error.  Also, we saw how our Support Engineers troubleshoot and fix Cloudflare 504 gateway timeout error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

If you’ve ever visited a website that serves you on an error page, you would have experienced how frustrating it is classified as the most frustrating thing you can do as a brand doesn’t meet your target audience’s needs and expectations. If you’re a website visitor, you would have probably viewed an error page when the users are looking for help or information. They couldn’t get frustrated and lose trust in your brand, permanently damaging your reputation.

The 504 Gateway Timeout Error is considered one type of error that can hurt the usability experience in such a manner. It will help you avoid the loss of brand sentiments and customer trust. We’ve discussed which type of error it means and the common causes and solutions to improve your website with effective technical SEO. You need to start by conducting this activity. In other words, 504 errors indicate a different computer, the one that your website is getting the message on doesn’t control. Still, it heavily relies on and isn’t communicating with it in a fast-paced environment.

What is a 504 Gateway Timeout Error?

A 504 Gateway Timeout Error can be highlighted in the internet browser window, similar to normal web pages. The 504 error highlights a problem with your network connection or server communication speed. 

When the browser sends an HTTP request to the server, it doesn’t receive a response from the upstream server in time to complete the request. Thus the request is “timed out.” Since a 504 Gateway Timeout Error is rather considered a generic format, it doesn’t actually pinpoint the exact cause of the problem. If this happens, your website will serve an error web page to your site’s visitors.

How You Might See the 504 Error?

If you are looking into individual websites are allowed to customize how they show a “gateway timeout” errors, but here are the most common ways that you’ll see one spelled out error:

  • 504 Gateway Terminal
  • HTTP 504
  • 504 ERROR
  • Gateway Timeout (504)
  • HTTP Error 504 – Gateway Timeout
  • Gateway Timeout Error

A 504 Gateway Timeout error is displayed in the internet browser window, similar to what the normal web pages do. There would be a website’s familiar headers and footers, and it seems to be a very nice English message on the page, or it could show up on an all-white page with a big 504 at the top. It shows an instinctive and identical same message, regardless of how the website happens to show it.

What are the Causes of 504 Gateway Timeout Errors

Most of the time, the question arises what does 504 gateway timeout errors  mean, it refers to whatever other server is taking so long that its “timing out” is probably down or not working properly. Since this error is based on a network error between servers on the internet or an issue with an actual server, the problem is probably with your computer, device, or internet connection. Hence, there are certain things that you can try in the case of fixing the HTTP 504 gateway timeout error.

How Do I Fix the Fix the 504 Gateway Timeout Error?

If you see a 504 Gateway timeout error, you might be confused about what to do further? You can always try the following steps:

1. Try to Reload the Page 

The foremost thing you should do when you face the HTTP Error 504 Gateway Timeout is to simply wait for a minute and reload the page. Regardless, the hosting or server merely is overloaded, and the site will quickly return to work. 

In another instance, you can easily check your website status on a specific website. This site will inform you if the site is out of service only for you or for all the visitors. The tools easily check the HTTP status code that is returned by the server. If the code differs from 200, then, in this case, you will see the done pointer. It will mean that the site doesn’t work for everyone.

2. Try a Different Browser

In such a case, the site is online, but you still see the HTTP Error 504 Gateway Timeout. You need to try changing your browser to another one. You must clear the browser cache or use the incognito mode, this can also help the user to determine if the error is caused by the browser.

3. Check on Different Devices 

Try opening the site on different computers, on different networks, or on mobile devices. If nothing could help to fix the Error 504 gateway timeout, this step will help you to determine if the problem is on the server-side or it is local.

4. Disable the Proxy

Disable the Proxy

Sometimes you might receive an HTTP 504 error code if you use a proxy server. These cases are quite rare, especially on the client-side. You need to read the guidelines on how to disable proxy on Windows and Mac.

5. Check DNS Records Propagation

Sometimes, HTTP Error 504 gateway timeout often causes a few problems with the DNS server. There are two reasons for that on the server side, it happens whenever the domain name isn’t changed to the correct IP address. If you’ve shifted the WordPress website to a new hosting domain, it’s essential to wait until the address will be implemented to the DNS base. In certain cases, it covers upto 24 hours. It merely depends on your DNS records TTL value. 

Also, you can use a freemium tool such as DNSMap to check whether your DNS has been spread across the world. The second DNS issue relates to the client-side, in this case, you can clear your local DNS cache. This is similar to clearing the browsing cache. 

In Windows, you need to simply open a command line and type the following instances

Check DNS Records

Also you should see the “Successfully flushed the DNS Resolver Cache” message.

Using the MacOS, type the following in the terminal:

  • dscacheutil -flushcache

Note: there aren’t any messages of successful functions on Mac.

Ultimately, you can temporarily change your client’s DNS servers. By default, DNS servers are provided by your Internet Service Provider. Also it enables users to temporarily change them to a public DNS server, for example provided by Google. There are certain people who usually prefer to use Google’s public DNS constantly because in certain cases that is more reliable and versatile to proceed ahead. Some people prefer to use Google’s public DNS constantly because in certain cases they are more reliable. 

6. Temporarily Disable the CDN

Also, the problem that you might relate to the content delivery network, if you use a third-party CDN provider, you can try to temporarily disable it. For that purpose, you may use WordPress plugins, with them you will be able to disable the CDN safely. If you use the backproxy services such as Cloudflare or Sucuri, they may cause the 504 gateway timeout error as they use the extra firewall. 

Mostly cache 500 state codes when they are returned by your source server, as users tend to notice the issue on Cloudflare’s freemium plan. Significantly, Cloudflare is a complete proxy service that provides you the fastest way to disconnect it. Although, before blaming cloudflare, it is essential to know that there are two type of 504 gateway timeout errors:

7. 504 Gateway Timeout in Cloudflare (Version 1)

Fix the 504 Gateway Timeout Error?

If you see a similar page like this, then in this case, the problem is on the Cloudflare side. You can contact their user support or check their status page. More particularly, they have already been notified about this problem and are working on it. 

8. 504 Gateway Timeout in Cloudflare (version 2)

504 Gateway Timeout in Cloudflare

If you see the page appearance like the above one, then this is an issue with your WordPress hosting provider. Users can follow the recommendations in the next step.

Identify the Problems with your Hosting Provider:

The servers encounter certain problems that are one of the common reasons as to why the users experience 504 errors on their WordPress website. In simple terminology, Nginx or Apache waits for a significant response until the waiting time has expired.

504 errors are classified as one of the popular onsites with a lot of visitors, online sites, and online stores. The latter may have installed popular eCommerce plugins such as WooCommerce. They would have many non-cached requests that can cause the servers to overlead. 

Although, such errors can happen to a variety of website categories that includes blogs and vice versa. Most of the hosters usually offer to upgrade to a more expensive tariff plan to sort out this problem, and even if this usually assists you to solve this issue, it is often not necessary and essential to proceed ahead.

Conclusion

Certainly, there are a variety of ways and methods to fix HTTP 504 gateway timeout errors on the WordPress site. Typically, this is an issue with the server, and in such circumstances, you need to contact your hosting provider to solve them. But it is essential to remember that they can also be caused via third-party plugins on the queue or backlog overflow for your web developers. Hence, you can know more about HTTP Status Codes via reading online.

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. For many blogs and ecommerce platforms, knowing how to fix server errors like this is crucial to keep their hard-earned visitors from bouncing to competitor sites.

As the 504 Gateway Timeout error doesn’t tell you why it occurred, it’s hard to pinpoint what’s causing the server timeout. This article will help you understand it in detail, learn how to diagnose its cause, and then fix it.

After trying all the various solutions mentioned in the post, your site should be up and running in no time.

Sound interesting? Let’s dive in!

Check Out Our Video Guide To Fixing the 504 Gateway Timeout Error on Your Site

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. 🤔 Learn how to fix it with this guide quickly. ⬇️Click to Tweet

What Is the 504 Gateway Timeout Error?

The 504 Gateway Timeout Error indicates that the server didn’t receive a timely response from an upstream server it needed to access in order to complete a request. This can happen because the other server is not functioning properly, overloaded, or down.

To simplify it further, this error occurs when two servers are involved in processing a request. The first server (typically the main server) times out, waiting for a response from the second server (upstream server).

Error Code 504 Gateway Timeout Error
Error Type Server-side
Error Variations 504 Gateway Timeout504 Gateway Timeout NGINX
NGINX 504 Gateway Timeout
Gateway Timeout Error
Error 504
HTTP Error 504
HTTP Error 504 — Gateway Timeout
HTTP 504
504 Error
Gateway Timeout (504)
Error Causes Server connectivity issues
Network connectivity problems
DNS issues
Firewall issues

This is how the process works: every time you visit a website in your browser, the browser sends a request to the web server where the site is hosted. The server processes the request and responds with the requested resources.

Illustration of how HTTP requests and responses work

How HTTP requests and responses work.

The server response includes one of many HTTP status codes to indicate the response’s status to the browser. But not all these HTTP status codes are errors. For instance, a 200 OK status code means that the server processed the request successfully and “Everything is OK.”

The 5xx class of HTTP status codes indicates that something’s wrong with the server, the server is aware of it, and it cannot carry out the client request. As a result, they’re also referred to as Server Error 5xx status codes.

Officially, five status codes are specified under the 5xx class (500, 501, 502, 503, 504). You may come upon many unofficial codes too (506, 507, 509, 520, etc.).

The 504 Gateway Timeout error manifests itself in various forms. Here are some ways it usually shows up:

The HTTP ERROR 504 in Chrome browser

The ‘HTTP ERROR 504’ in the Chrome browser.

The 504 Gateway Timeout error is similar to the 502 Bad Gateway error, which indicates that the first server received an invalid response from the second server (upstream server).

504 GATEWAY TIMEOUT status code in Chrome DevTools

The ‘504 GATEWAY TIMEOUT’ status code in Chrome DevTools.

Variations of the 504 Gateway Timeout Error

The browser displays any 504 Gateway Timeout error inside it, just like any other error. As there are various operating systems, web servers, browsers, and user agents, it can show up in multiple ways.

Below are a few common 504 error message variations that you may run into:

  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • Gateway Timeout Error
  • Error 504
  • HTTP Error 504
  • HTTP Error 504 — Gateway Timeout
  • HTTP 504
  • 504 Error
  • Gateway Timeout (504)
  • This page isn’t working — Domain took too long to respond
  • 504 Gateway Time-out — The server didn’t respond in time
  • The page request was canceled because it took too long to complete
  • Site visitors: There was an issue serving your request, please try again in a few minutes.
  • Site Owners: There was a gateway timeout. You should visit your error log for more information.
  • A blank white screen

All the above error responses, though worded differently, point to the same 504 Gateway Timeout server error.

Web servers and websites can customize how they show the 504 Gateway Timeout error to users. Some of them can be cool! It’s an excellent tactic to quell their visitors’ disappointment.

GitHub’s customized HTTP 504 error page

GitHub’s customized HTTP 504 error page.

What Are the Causes of the 504 Gateway Timeout Error?

As the 504 error is due to a timeout between servers, the problem probably isn’t with the client’s device or internet connection. That also includes your device and connection.

A 504 Gateway Timeout error indicates that the web server is waiting too long to respond from another server and “timing out.” There can be many reasons for this timeout: the other server is not functioning properly, overloaded, or down.

The other server need not always be external (e.g. CDN, API gateway). It can also be a server-like entity within the main web server (e.g. reverse proxy server, database server).

SEO Impact of the 504 Gateway Timeout Error

All 5xx errors prevent a webpage from loading, making them detrimental to user experience. Hence, search engines like Google take these errors seriously. If the error persists for a long duration, it may even lead to deindexing the webpage from the search engine results.

For example, when Google spiders stumble upon a 503 Service Unavailable error, they’ll understand that it’s a temporary issue as it’s mostly used to enable site maintenance mode. Thus, they’ll try to crawl the page again later.

A 504 Gateway Timeout error isn’t necessarily temporary as it can be due to multiple reasons. If your site is down for just a few minutes, and if the spiders are trying to crawl it multiple times every minute, they’ll try to serve the page from their cache.  They wouldn’t even notice it.

But if your site is down for 6+ hours or more, then Google will consider the 504 error as a serious site-wide issue that you need to fix as soon as possible. This can impact your SEO negatively.

Viewing the crawl errors in Google Search Console

Viewing the crawl errors in Google Search Console

Google Search Console is one of the best SEO tools to monitor your website’s HTTP 5xx errors.

How to Fix the 504 Gateway Timeout Error?

Without knowing exact details about the site, such as its server configuration, hosting plan, third-party plugins, and the traffic it attracts, you may find it frustrating and overwhelming to fix a 504 Gateway Timeout error.

Since many variables are involved, I recommend you to start by fixing client-side issues, which are pretty rare, and then move towards fixing server-side problems. They’re usually the culprits with 504 errors.

1. Try Reloading the Webpage

One of the first things you can try when encountering a 504 Gateway Timeout error is to wait a few minutes and try reloading the page.

You can press the F5 keyboard shortcut to refresh/reload the webpage in most browsers. To remove the page’s browser cache before reloading, you can press the CTRL+F5 shortcut combo instead.

Refreshing a webpage in Chrome browser

Refreshing a webpage in Chrome browser

While you’re at it, you can also try loading the site in a different browser to rule that out as an issue. As most 504 errors are due to temporarily overloaded servers, using this solution should make your site come right back.

If waiting and reloading the site doesn’t fix the 504 error issue, you can check whether a site is down for everyone or just you. Two useful online tools to test a site for downtime are Down for Everyone or Just Me and Is It Down Right Now?

Testing Kinsta.com on Down for Everyone or Just Me

Testing Kinsta.com on Down for Everyone or Just Me

2. Reboot Your Network Devices

Sometimes, problems with your network devices like modem or router could lead to a 504 Gateway Timeout error. Rebooting these devices could help you with fixing the problem.

While you can switch off all these networking devices in any order, the order you switch them back on is important. Typically, turn these devices on from the “outside-in,” following the connection order from the internet service provider to your main client device.

3. Check Your Proxy Settings

A proxy server sits between your device and the internet. It’s mostly used to enhance online privacy by hiding private information (e.g. device location) from websites and webservers (e.g. using a VPN).

While it’s rare for proxy servers to cause a 504 error, incorrect proxy server settings can sometimes be the reason. You can disable the proxy server and try reloading the webpage to see whether it’ll fix the error.

Changing the ‘Proxy’ settings in Windows 10

Changing the ‘Proxy’ settings in Windows 10

Most clients don’t use a proxy service, so you can skip this step if you’re confident that you don’t use any proxy server. However, you might have set it without you even knowing about it. I’d suggest you check your device’s and browser’s proxy settings to rule this cause out.

4. Check for DNS Issues

A 504 Gateway Timeout error can also be caused by DNS issues on the server-side or the client-side (or both).

The most probable reason for a server-side DNS issue is the FQDN (fully qualified domain name) not resolving the correct IP address or the DNS server not responding. Usually, this occurs when you’ve just migrated your site to a new server or host. Hence, it’s important to wait for the domain’s DNS records to propagate fully, which can take up to 24 hours.

You can use free tools like whatsmydns.net DNS Checker or DNSMap to see if your DNS has propagated around the globe.

Checking DNS propagation for your domain on whatsmydns.net

Checking DNS propagation for your domain on whatsmydns.net

For fixing client-side DNS issues, you could try flushing your local DNS cache. It’s like clearing your browser cache, except here, you’re flushing the DNS cache from the operating system.

If you’re using Windows, you can flush the DNS cache by opening the Command Prompt and entering the following directive:

ipconfig /flushdns

Flushing the DNS Cache with Command Prompt

Flushing the DNS Cache with Command Prompt in Windows

You should see a “Successfully flushed the DNS resolver Cache.” message if it worked.

For the latest macOS versions, you can open the Terminal and run the following command:

sudo killall -HUP mDNSResponder

You won’t see any notification in macOS when the process finishes, but you can change that by appending the command with your custom message.

sudo killall -HUP mDNSResponder; DNS Cache was cleared successfully

If you’re using older macOS versions, the command you need to enter varies based on which version of macOS you’re running. For more details, you can refer to the macOS section in Kinsta’s in-depth flush DNS tutorial.

If you’re using the Linux operating system, then the process is quite similar to macOS as even Linux uses the Terminal as its command-line interface. Since there are many Linux distributions, the exact command you need to run may vary from one distro to another. You can check out Kinsta’s guide for more information.

Finally, you can change your client-side DNS servers temporarily. By default, your ISP assigns the DNS servers automatically to you. But you can change these to public DNS IPs temporarily.

Some reliable DNS servers you can try out are Google Public DNS, Cloudflare 1.1.1.1, Quad9 DNS, and Cisco OpenDNS.

Settings custom DNS servers in Windows 10

Settings custom DNS servers in Windows 10

5. Disable Your Site’s CDN Temporarily

Sometimes, the issue could also be with your content delivery network (CDN). If a site’s origin server isn’t reachable, most CDNs will try to serve the full webpage from their cache.

But most CDNs don’t enable this feature by default as it’s complex to cache dynamic assets on most sites (e.g. the WordPress admin dashboard).

Setting the ‘Cache Everything’ page rule in Cloudflare

Setting the ‘Cache Everything’ page rule in Cloudflare

A straightforward way to troubleshoot this is to disable your CDN temporarily. For example, if you’re using the free CDN Enabler WordPress plugin to link your site assets to the CDN URLs, then you can deactivate the plugin and test reloading your site.

The same goes for using any other plugin you may use to connect to your CDN (e.g. WP Rocket, Breeze, W3 Total Cache).

If you can’t access your site’s admin dashboard, you can disable the plugin via SFTP by renaming the plugin’s folder name.

Disable all plugins via SFTP by renaming the plugins folder name

Disable all plugins via SFTP by renaming the plugins folder name

CDNs like Cloudflare or Sucuri, which provide full proxy services, have extra firewalls between their edge servers and your origin server. Hence, you may encounter HTTP 5xx errors more frequently while using them. Most of them cache 5xx errors returned by your origin server, so it’s easy to troubleshoot them.

Cloudflare’s free plan is prone to throw up a 5xx error. Unfortunately, since it’s a full proxy service, there’s no quick way to disable it. But before you blame Cloudflare for it, know that Cloudflare shows two variations of the 504 Gateway Timeout error.

504 Gateway Timeout at Cloudflare (Variation 1)

Cloudflare will show you a custom 504 Gateway Timeout error screen when your site’s origin server responds with a standard HTTP 504 response.

Cloudflare’s custom Error 504 screen

Cloudflare’s custom Error 504 screen

Here, the issue lies with your web server and not Cloudflare. You can try fixing it with the other solutions mentioned below or contact your hosting provider’s support for technical help.

504 Gateway Timeout at Cloudflare (Variation 2)

If Cloudflare causes the 504 Gateway Timeout error, the error screen will mention “cloudflare,” which is currently the standard server name for all Cloudflare assets. Usually, the error screen will appear as below:

504 Gateway Timeout error caused by Cloudflare

Error screen for 504 Gateway Timeout caused by Cloudflare

Since Cloudflare itself is unresponsive, you’ll not see any Cloudflare-branded error screen here.

Most likely, Cloudflare is already aware of the issue and is working on a fix already. You can confirm this by checking the Cloudflare System Status webpage. Alternatively, you can get in touch with Cloudflare support for a quicker resolution.

Check Cloudflare System Status at cloudflarestatus.com

Check Cloudflare System Status at cloudflarestatus.com

504 Gateway Timeout at Cloudflare Due to Large Uploads

The size of your uploads to your site can also be a reason for the server timeouts. Cloudflare limits upload file size (per HTTP POST request) to just 100 MB on both Free and Pro plans.

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

The issue can be on your host’s end or with Cloudflare. You can find out the exact cause by bypassing Cloudflare with your DNS hosts file and trying your upload again.

If you’re using Cloudflare with WordPress, I recommend using their free plugin and excluding critical URLs from caching (such as the WordPress admin dashboard). You can refer to Kinsta’s detailed post on how to configure Cloudflare settings for WordPress.

Suggested reading: How to Set up Cloudflare APO for WordPress.

6. Check Server Issues With Your Host

Server issues are one of the most common reasons for facing a 504 Gateway Timeout error. Since most WordPress sites are hosted on Nginx or Apache webservers, Nginx or Apache is waiting for a response from something and timing out.

Many clients come to Kinsta for exactly this problem they’re facing at other hosts. The conversation goes something like this:

We’re getting around 100k visitors per month with more than 200k views. Currently, we’re hosting with ____ and we experience 504 errors constantly due to server overload. I don’t like how ____ handled the problem, and we were also advised that we will have to move to their dedicated plans soon, which I believe is not necessary.

High-traffic and ecommerce sites are more prone to getting 504 errors because of server overload as they generate many uncacheable requests. However, this issue can crop with any site, including simple blogs. Many hosts will ask you to upgrade to a high-tier plan to fix the issue, which in most cases is unnecessary.

Kinsta uses LXD managed hosts and orchestrated LXC software containers for each site. Thus, every site is housed in its own isolated container with access to all the software required to run it (Linux, Nginx, PHP, MySQL). The resources are 100% private and aren’t shared with any other site, even your sites.

Most hosts providing shared hosting plans don’t have this capability. Hence, a high-traffic site hosted on the same server as yours may cause your site to throw up a 504 error too.

Apart from isolating each site in its container, Kinsta has also designed its infrastructure to handle thousands of concurrent connections easily. Kinsta even hosts the MySQL databases at localhost, not a remote server. This means no latency between machines, resulting in faster queries and fewer chances of timeouts occurring.

Many clients who migrate to Kinsta see huge decreases in overall load times.

A 212.5% increase in performance after switching to C2.

A 212.5% increase in performance after switching to C2.

An overloaded server isn’t the only cause for a server timeout. There can be many other reasons for the 504 error:

Slow Server Infrastructure

The server you use to host your site may not have enough resources to handle the load. It’s like playing a modern, graphics-intensive videogame on a decade-old PC.

The server just hangs up trying to serve the website. The only solution to this problem is to upgrade to a server with better infrastructure. For this reason, even Kinsta’s most basic hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic. If all the server’s PHP workers are busy, they’ll build up a queue.

When the queue gets too big, the server disregards old requests, which may cause the server to throw up a 504 gateway error. You can ask your host about increasing your number of PHP workers. This’ll allow your site to execute multiple requests simultaneously.

Firewall Issues

Your server’s firewall could have some errors or an improper configuration. Perhaps, a few of its rules prevent the server from establishing a connection properly. To know if your firewall is the culprit, you can check your server’s error logs.

Network Connectivity Problems

Connectivity issues between the proxy server and the web server could cause delays in responding to HTTP requests. If you use a load balancer, there could also be network connectivity issues with it.

HTTP Timeouts

HTTP timeouts can occur when a connection between the web server and the client is kept open for too long. With WordPress sites, this usually happens when running WordPress imports. One way to resolve this issue is to switch to a faster internet connection.

You can also use a tool with support for WP-CLI to run the scripts directly on the server, bypassing the HTTP connection entirely. For instance, you can use the wp import WP-CLI command to run the WordPress Importer plugin directly through the command-line interface.

Important: 504 Gateway Timeout errors look similar to 503 Service Unavailable errors or 502 Bad Gateway errors. But they’re all different. If you’re experiencing a 504 error at Kinsta, open a support ticket to get your issue fixed immediately.

For monitoring your site’s downtime on your own, you can use a tool like updown.io. It’ll check your website’s status (or any URL) periodically by sending an HTTP request to it. You can set the check frequency from 15 seconds to 1 hour. If your website isn’t responding correctly, it’ll notify you with an email or an SMS.

Monitor your website with updown.io

Monitor your website easily with updown.io

You’ll get a generous quantity of free credits with every account of updown.io, but if you’re looking for cheaper alternatives, you can check out WebGazer or UptimeRobot. Both these tools will help you monitor your site’s uptime every 5 minutes for free. That’s decent enough for most website owners.

WebGazer website monitoring tool's dashboard

WebGazer website monitoring tool’s dashboard

Monitoring your website will give you an idea of how often it’s down. This is especially helpful if you’re using a shared hosting provider. Most application, database, and managed WordPress hosts (like Kinsta) take care of this automatically for you. Hence it’s always recommended to go with them.

For a detailed explanation, check out Kinsta’s post on the importance of managed WordPress hosting.

7. Check for Spam, Bots, or DDoS Attacks

Malicious attackers can bring your web server to a crawl by sending too many and/or resource-intensive requests. If your site is getting spammed by bots or undergoing a DDoS attack, it can overwhelm your server and result in 504 Gateway Timeout errors for many genuine users.

You can look at your server traffic and analytics to see if you can spot any irregular patterns in the site traffic. If you’re using Kinsta to host your site, you can view this data easily by going to your MyKinsta Analytics dashboard.

Screenshot: Site-level Analytics in MyKinsta.

Site-level Analytics in MyKinsta.

Start your investigation by looking at the top client IPs. It’ll give you an idea of who generates the maximum number of requests, and from where. If your server suddenly uses up enormous bandwidth or attracts a lot of traffic, then this report will come in super handy.

Screenshot: Top client IPs displayed in MyKinsta Analytics dashboard.

Top client IPs displayed in Analytics dashboard.

Next, you can check out the Cache Analysis report. Here, you can see how many requests are bypassing or missing the cache, or being served from the cache. For performance and stability reasons, you want to cache as many requests as possible, but it’s not always possible to achieve that.

For example, WooCommerce sites generate many uncacheable requests for features such as the shopping cart and the checkout process.

The ‘Cache Analysis’ screen in MyKinsta

The ‘Cache Analysis’ screen in MyKinsta

Finally, you can use a security plugin to beef up your website’s security by spotting and blocking worrisome traffic/IPs. You can ask your host to block certain IPs too.

Depending upon the length and scale of the attack, this could be a never-ending process of blacklisting IPs as many attackers change their IPs and proxy addresses after getting blocked.

Note: Kinsta doesn’t allow its clients to install security plugins as they can have a huge effect on the site’s performance, especially its scanning capabilities. As Kinsta uses load balancers with Google Cloud Platform, blocking IPs wouldn’t always work as intended.

You can use dedicated security solutions such as Cloudflare or Sucuri to protect your sites from DDoS attacks and spambots. For more, you can check out Kinsta’s articles on how to install Cloudflare on your site and how Sucuri helped stop a DDoS attack in its tracks.

8. Repair Your Corrupted WordPress Database

Sometimes, a 504 Gateway Timeout error can be because of a corrupt database, especially in WordPress sites. Typically, this is due to corrupted database tables or files. Sometimes, it can also be caused by a serious security issue like your site or database being hacked.

Repairing a corrupted WordPress database depends on the problem. Plugins like WP-DBManager make it easy to diagnose database issues and repair them. I recommend you to read Kinsta’s detailed walkthrough on repairing WordPress database issues to get started.

9. Check Your Site’s Plugins and Themes

In most cases, third-party plugins and themes don’t cause 504 errors. But there’s a slight chance that they might cause server timeouts, usually by queuing up many uncached requests generated by the plugin/theme. As this ties up a lot of your server’s PHP workers, it can cause 504 errors.

A great example of this issue is WooCommerce, a plugin installed to add ecommerce functionality to WordPress sites.

The simplest way you can troubleshoot this problem is by deactivating all your plugins. Remember, you won’t lose any data if you just deactivate a plugin.

If you can access your admin dashboard, you can go to the Plugins screen, select Deactivate from the bulk actions menu, checkmark all the plugins, and then hit the Apply button. This will disable all of your plugins.

Deactivate plugins in WordPress

Deactivating all the WordPress plugins through WP admin dashboard

If you can’t access your admin area, you can disable plugins via SFTP using the method described before. Just rename the main plugin folder name to disable all the plugins in bulk.

Once you’ve deactivated all the plugins, check whether your site loads properly. If it works, you must activate each plugin, testing the site after enabling every plugin.

Finally, make sure that your plugins, themes, and WordPress core are up to date. Also, ensure that your server is running the recommended version of PHP.

If you feel this to be too overwhelming, you can always reach out to your host for help. Kinsta uses Kinsta APM and other troubleshooting techniques to help clients narrow down what plugin, query, or script might cause the error.

In the worst-case scenarios, like an inefficient query or bad code in a plugin/theme, you can bring in a WordPress developer to fix the issue.

10. Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your site. This can help you narrow down an issue on your site quickly, especially if it’s resulting from a demanding plugin on your site.

If you’re a Kinsta customer, you can easily see logged errors in the MyKinsta dashboard. Start by selecting WordPress Sites in the sidebar menu, choose the site you want to examine, then select Logs to open the Log viewer page.

Screenshot: Viewing the error log within the MyKinsta dashboard.

Viewing the error.log file within the MyKinsta dashboard.

If your host doesn’t have a logging tool, then you can enable WordPress debug mode by adding the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

The WP_DEBUG constant enables or disables the WordPress debug mode. It has two optional companion constants that can extend its features. The WP_DEBUG_LOG constant directs all errors to be saved to a debug.log file within the /wp-content/ directory. If you don’t see this file, you can always create one.

The WP_DEBUG_DISPLAY constant controls whether debug logs show up on the HTML page. Setting this to false will hide all errors, but you can review the errors later, as you’ve also defined WP_DEBUG_LOG as true.

Important: If you have WP_DEBUG enabled in the Kinsta environment, it’ll route all errors to the debug.log file and not the error.log in the MyKinsta dashboard.

You can also download the raw WordPress error log files via SFTP. Typically, you can find error logs in your server’s root directory in a folder named “logs.”

Accessing the WordPress error logs folder via SFTP

Accessing the WordPress error logs folder via SFTP

Kinsta users can also enable WordPress debug mode from their MyKinsta dashboard. To do that, navigate to Sites > Tools > WordPress Debugging and click the Enable button. This will allow you to see PHP errors and notices without enabling debug mode via SSH or SFTP.

Lastly, you can check the server log files. Depending on which server you’re using to host your WordPress site, they’re commonly found in these locations:

  • Apache: /var/log/apache2/error.log/
  • Nginx: /var/log/nginx/error.log/

You can refer to logging related documentation of Apache or Nginx for more information.

11. Configure Apache or Nginx Settings Properly

You can edit your server config files to increase resource limits for specific directives. This can help you resolve the 504 Gateway Timeout error.

For Apache Webservers

First, add the following code to your httpd.conf:

TimeOut 600

This setting defines how long the server will wait for certain requests before marking it as a network timeout issue. Its default value is 60 seconds (Apache 2.4 version).

You can only add this directive in your httpd.conf file, not in your .htaccess file. Since most shared hosting providers don’t allow you to modify the httpd.conf file, you can try increasing the value of the LimitRequestBody directive in your .htaccess file instead.

Then add the following line to your php.ini file:

max_execution_time 300

The default value of PHP’s max_execution_time directive is 30 seconds. Increasing it will allow your site’s PHP scripts to run longer.

For Nginx Webservers

If you’re running your WordPress sites on Nginx + FastCGI Process Manager (PHP-FPM) or using Nginx as a reverse proxy for Apache, you can tweak the server settings to help prevent 504 Gateway Timeout errors.

504 Gateway Timeout Error on Nginx + FastCGI (PHP-FPM)

First, you must edit your PHP-FPM pool config file. You can find it at the /etc/php7.4/fpm/pool.d/www.conf location in your Nginx server (the exact path may vary based on the PHP version). Alternately, you can run the following command in your terminal to edit the PHP-FPM pool config file:

sudo nano /etc/php/7.2/fpm/pool.d/www.conf

Next, set the following directive:

request_terminate_timeout = 300

After this, you must edit your php.ini file. You can locate it at /etc/php.ini. Open the file and add/change the value for the max_execution_time directive to 300 seconds.

max_execution_time = 300

Finally, add the following code to your nginx.conf file’s location block:

location ~ .php$ {
...
fastcgi_read_timeout 300;
}

Reload Nginx and PHP-FPM for the changes to take effect.

sudo service nginx reload
sudo service php7.4-fpm reload

The exact code to reload PHP-FPM will vary based on the PHP version installed on your server. Test your site to see whether it has fixed the issue.

504 Gateway Timeout Error on Nginx Proxy

If you’re using Nginx as a reverse proxy server for Apache, then you can make it more lenient towards server timeouts by adding the following directives to your nginx.conf file:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Don’t forget to reload Nginx after making your changes.

sudo service nginx reload

Other HTTP Errors Like 504 Gateway Timeout

As mentioned earlier in the article, many other HTTP 5xx errors are just like the 504 Gateway Timeout error. It’s because they all happen on the server-side. These errors include:

  • 500 Internal Server Error
  • 501 Not Implemented Error
  • 502 Bad Gateway Error
  • 503 Service Unavailable Error

Other HTTP errors caused due to client-side issues, like the 404 Not Found error, are also like the 504 error. You can refer to Kinsta’s detailed guide and list of HTTP status codes for more information.

When you don’t know what caused a 504 Gateway Timeout error, how do you fix it in time to keep hard-earned visitors from bouncing to competitor sites? 🤷‍♂️ All the details are in this post. ⬆️Click to Tweet

Summary

Your site can be affected by the 504 Gateway Timeout error because of multiple reasons. In this article, you learned how to troubleshoot them all. Typically, these errors are caused due to server-side issues, in which case you can reach out to your host and get it resolved quickly.

However, you must also understand that this error can be due to third-party plugins, themes, services, inefficient database queries, or a combination of two or more of these. If you’re maxing out your server’s resources (e.g. PHP workers), it’s recommended to optimize your site for performance.

If you still find that your website is timing out, then it might very well be that you need to upgrade your hosting plan or the number of PHP workers. I recommend you to consider this option only after you’ve exhausted all the other solutions described in this article.

From simple static sites to complex ecommerce and membership sites, Kinsta’s scalable hosting plans are designed to accommodate all types of websites. To learn more about our scalable cloud hosting, check out this article on the most important things you should know about Kinsta!

Did we miss anything? If you’re still finding it difficult to fix the 504 Gateway Timeout error on your site, leave a comment below.

Нет ничего более раздражающего, чем появление белого экрана с ошибкой при обращении к WordPress сайту. Некоторые из распространенных ошибок, с которыми вы могли сталкиваться ранее: белый экран смерти, ошибка установки соединения с базой данных и т.д. Для большинства блогов, а также сайтов, связанных с электронной коммерцией, появление таких ошибок приводит к потере дохода, поскольку посетители сразу покидают такой ресурс, а клиенты не могут совершить покупки. Сегодня мы рассмотрим ошибку 504 Gateway Timeout Error, а также дадим рекомендации по поводу того, как справиться с ней на своем WordPress сайте. Читайте далее о причинах этой ошибки и о том, как предотвратить ее появление.

Содержание

  1. Почему появляется 504 Gateway Timeout Error?
  2. Варианты ошибки 504 Gateway Timeout Error
  3. Попробуйте перезагрузить страницу.
  4. Отключите параметры прокси.
  5. Проблемы с DNS.
  6. Временно отключите CDN
  7. Проблемы с сервером (проверьте ваш хост)
  8. Спам, боты и DDoS-атаки
  9. Проверьте ваши плагины и темы.
  10. Проверьте логи.
  11. Параметры Nginx
  12. Заключение

Почему появляется 504 Gateway Timeout Error?

Перед тем, как мы рассмотрим саму ошибку, важно понять, из-за чего она появляется. Всякий раз, когда вы запускаете свой браузер и посещаете сайт, он передает запрос обратно на сервер, на котором размещен. Затем веб-сервер обрабатывает запрос и отправляет вам запрашиваемые ресурсы вместе с HTTP-заголовком. Этот заголовок содержит один из многочисленных кодов состояния HTTP, который позволяет понять, все ли в порядке или что-то пошло не так. Далеко не все коды состояния плохие. К примеру, код состояния 200 говорит о том, что все в порядке.

Существует много различных кодов ошибок 500 (500, 501, 502, 503, 504 и т.д.), которые имеют разное значение. Они указывают, что запрос был принят, но сервер не смог выполнить его.

В данном случае ошибка 504 означает, что «для сервера, работающего в качестве шлюза, вышло время ожидания ответа от другого сервера». Код возвращается, когда есть два сервера, участвующих в обработке запроса, и время ожидания ответа от второго сервера со стороны первого сервера истекло (RFC 7231, раздел 6.6.5).

Варианты ошибки 504 Gateway Timeout Error

Вследствие многообразия веб-браузеров, операционных систем и серверов ошибка 504 может быть представлена разными способами. Все они, как правило, несут в себе одно и то значение. Ниже приведены некоторые из вариантов, с которыми вы можете столкнуться:

  • “504 Gateway Timeout”
  • “504 Gateway Timeout NGINX”
  • “NGINX 504 Gateway Timeout”
  • “Gateway Timeout Error”
  • “Error 504”
  • “HTTP Error 504”
  • “HTTP Error 504 – Gateway Timeout”
  • “HTTP 504”
  • “504 Error”
  • “Gateway Timeout (504)
  • “504 Gateway Time-out – The server didn’t respond in time”

Как справиться с ошибкой 504 Gateway Timeout Error

С чего следует начать решение проблем, если вы столкнулись с ошибкой 504 Gateway Timeout Error на своем WordPress сайте? Не имея контекста, достаточно сложно понять, что делать в первую очередь. Как правило, ошибку вызывают проблемы с сетевым подключением и проблемы с сервером, на котором расположен сайт. Однако ошибка может быть следствием проблем на стороне клиента или даже результатом использования стороннего плагина. Мы немного углубимся в этот вопрос. Давайте ознакомимся с популярными причинами появления ошибки, а также рассмотрим то, как исправить ее.

  1. Попробуйте перезагрузить страницу.

Одна из первых вещей, которую вы должны сделать, столкнувшись с ошибкой 504 Gateway Timeout Error – это просто подождать минуту и перезагрузить страницу. Возможно, хостинг или сервер просто перегружен, и сайт быстро вернется в работу. Вы можете также попробовать другой браузер.

Еще одна вещь, которую вы можете сделать – это проверить статус вашего сайта на downforeveryoneorjustme.com. Этот сайт подскажет вам, вышел ли сайт из строя только у вас или же у всех посетителей. Инструмент проверяет код состояния HTTP, который возвращается сервером. Если код отличается от 200, то в таком случае вы увидите указатель Down (т.е. сайт «лежит» для всех).

  1. Отключите параметры прокси.

Иногда вы можете столкнуться с ошибкой 504, если вы используете прокси-сервис. Эти случаи являются очень редкими, особенно на стороне клиента. Однако иногда такие настройки могут быть установлены без ведома клиента. В сети есть руководства, посвященные отключению настроек прокси на Windows и Mac.

  1. Проблемы с DNS.

Ошибка 504 gateway timeout может быть вызвана проблемами с DNS. Такая ошибка может возникать с двух сторон. На стороне сервера она происходит, к примеру, когда домен не преобразован в корректный IP. Если вы только что перенесли свой сайт WordPress на новый хостинг, то важно дождаться распространения DNS. Обычно это занимает до 24 часов. Все зависит от значения TTL ваших DNS-записей. Вы можете использовать бесплатный инструмент, такой как DNSMap, чтобы проверить, распространились ли ваши DNS по всему миру.

Вторая проблема с DNS связана уже с клиентской стороной. В этом случае вы можете очистить свой локальный DNS кэш. Это похоже на очистку кэша браузера.

В Windows просто откройте командную строку и введите следующее:

ipconfig /flushdns

Вы должны увидеть сообщение «Successfully flushed the DNS resolver Cache».

В macOS введите следующее в терминал:

dscacheutil -flushcache

Примечание: на Mac нет сообщений об успешном завершении.

И, наконец, вы можете временно изменить ваши клиентские DNS-серверы. По умолчанию DNS-серверы автоматически привязываются вашим интернет-провайдером. Вы можете временно сменить их на публичный DNS-сервер, такой как Google. Некоторые предпочитают постоянно использовать публичные DNS Google, поскольку они в некоторых случаях могут быть более надежными.

  1. Временно отключите CDN

Также проблема может связана с CDN (сетью доставки контента). Если вы используете стороннего CDN провайдера, вы можете просто временно отключить ваш CDN. К примеру, нам нравится бесплатный плагин CDN Enabler. Если вы используете его, вы можете просто отключить плагин, чтобы проверить работу сайта. Перестали попадать в консоль WordPress после этого? В таком случае войдите на сайт через SFTP и переименуйте папку с плагином в cdn-enabler_old. В итоге ваше CDN соединение будет временно отключено. То же самое касается плагина WP Rocket или любого другого плагина, который подцеплялся к CDN.

Иногда эта ошибка может быть следствием использования прокси-сервисов, таких как Cloudflare или Sucuri, поскольку у них есть дополнительные файрволы. Большинство из них кэшируют коды состояния 500, когда они возвращаются вашим исходным сервером. Мы заметили, что это время от времени происходит на бесплатном тарифе Cloudflare. К сожалению, поскольку Cloudflare является полным прокси-сервисом, быстрого способа его отключения не существует.

Однако, прежде чем грешить на Cloudflare, важно знать, что есть два типа ошибки 504:

504 Gateway Timeout в Cloudflare (вариант 1)

Если вы видите следующую страницу, то в данном случае проблема на стороне Cloudflare. Обратитесь к ним в поддержку. Либо проверьте их страницу со статусом. Скорее всего, они уже уведомлены о данной проблеме и работают над ней.

504 Gateway Timeout в Cloudflare (вариант 2)

Если вы видите следующую страницу, то это проблема с вашим хостом WordPress (исходный сервер), и в этом случае вам нужно воспользоваться рекомендацией под номером 5.

  1. Проблемы с сервером (проверьте ваш хост)

Проблемы с сервером – одна из распространенных причин, почему пользователи сталкиваются с ошибками 504 на своих WordPress-сайтах. Говоря простым языком, Nginx или Apache ожидают ответа от второй стороны, и время ожидания истекло.

Ошибки 504 чаще всего встречаются на сайтах с высоким трафиком и на сайтах электронной коммерции (с установленным WooCommerce, к примеру), у которых много некэшируемых запросов. Это может вызывать перегрузку сервера. Однако мы сталкивались с такими ошибками на разных типах сайтов, в том числе и на обычных блогах. Многие хостинги отвечают стандартными фразами по типу «вам нужно перейти на более дорогостоящий тарифный план, чтобы исправить эту проблему». И пусть это обычно помогает решить данную проблему, зачастую это не является необходимым.

Хостинги, такие как, к примеру, Kinsta, используют контейнеры LXD для каждого сайта. Это означает, что каждый сайт размещается в своем изолированном контейнере, в котором имеются все необходимые программные ресурсы, требуемые для его запуска (Linux, Nginx, PHP, MySQL). Ресурсы на 100% конфиденциальны и не делятся ни с кем. Многие виртуальные хостинги WordPress не имеют данной возможности, поэтому любой соседний сайт с высоким трафиком будет вызывать ошибки 504 на вашем сайте.

В Kinsta инфраструктура построена так, чтобы легко обрабатывать тысячи одновременных подключений. Даже базы данных MySQL размещаются на локальном хосте, а не на удаленном сервере. Это гарантирует отсутствие задержки между машинами, что приводит к более быстрым запросам и меньшей вероятности возникновения тайм-аута между ними.

Помимо тайм-аутов сервера из-за повышенной нагрузки есть и другие причины, в результате чего может возникнуть ошибка 504:

  • Медленный сервер. Вполне возможно, что сервер, на котором расположен ваш WordPress сайт, слишком медленно отвечает на запросы, и поэтому он генерирует ошибки шлюза.
  • Недостаточно PHP воркеров. PHP-воркеры используются для выполнения кода на вашем WordPress-сайте. На требовательных в плане ресурсов сайтах вполне может быть так, что все PHP-воркеры заняты, и в этом случае они начинают формировать очередь. Если очередь и бэклог заполнены, старые запросы начинают игнорироваться. Вы можете попросить ваш хостинг увеличить количество PHP-воркеров. Дополнительные PHP-воркеры для сайта позволяют одновременно выполнять несколько запросов.
  • Проблемы с файрволом. Файрвол на вашем сервере может содержать ошибки в результате неверной конфигурации или правил, препятствующих установлению соединения.
  • Сетевое подключение. Если возникают проблемы с сетевым подключением между прокси-сервером и веб-сервером, то это может вести к задержкам с ответом для HTTP-запросов. Также могут возникать сетевые проблемы с балансировщиком нагрузки, если он используется.

Также важно отметить, что ошибки 504 могут обманчиво выглядеть как ошибки 503 (сервис недоступен) или даже ошибки 502 (bad gateway), но на практике они отличаются.

Если вы хотите предотвратить появление таких ошибок в будущем, вы можете воспользоваться инструментом, таким как updown.io, для отслеживания ситуации и немедленного уведомления о любых проблемах. Сервис периодически отправляет HTTP HEAD-запрос к указанному URL. Вы можете просто задать вашу главную страницу. Можно задавать частоту проверок:

  • 15 сек
  • 30 сек
  • 1 мин
  • 2 мин
  • 5 мин
  • 10 мин

Он пришлет вам электронное письмо, если ваш сайт перестал работать, с указанием времени, когда это случилось. Ниже приведен пример:

Это может быть особенно полезно, если вы используете виртуальный хостинг, который, как правило, работает на пределе возможностей. Это даст вам доказательство того, что ваш сайт не работал (к примеру, ночью). По этой причине мы и советуем переходить к администрируемым (управляемым) хостингам.

  1. Спам, боты и DDoS-атаки

Может быть так, что ваш сайт был заспамлен ботами или подвержен DDoS-атаке. Иногда это ведет к некэшируемым запросам и, как следствие, к перегрузке сервера, что и выливается в ошибку 504 gateway timeout. Вы можете изучить аналитику сервера, чтобы увидеть, есть ли в ней какие-либо паттерны. В Kinsta имеется, к примеру, инструмент MyKinsta для аналитики. Вы можете попросить эти данные у вашего хостинга.

Первый отчет, который мы советуем изучить – это IP-адреса топовых клиентов. Обычно это очень полезно, особенно если ваш сайт внезапно стал генерировать большой трафик или попал под атаку ботов.

Второй отчет, который мы рекомендуем посмотреть – это запросы и боты. Вы можете быстро сравнить количество людей, попадающих на ваш сайт, с количеством ботов и роботов. Однако помните, что не все боты плохие. GoogleBot – пример хорошего бота, он сканирует сайт для индексации содержимого в результатах поиска.

Третий отчет, который мы рекомендуем посмотреть – это анализ кэша. Здесь вы можете видеть, какие запросы отсутствуют в кэше, а также каковы топовые локации вашего сайта. По причинам производительности и стабильности вы должны стараться закэшировать как можно больше запросов. Это не всегда возможно, поскольку некоторые сайты генерируют большое количество некэшируемых запросов (как в случае с WooCommerce), и они нужны для того, чтобы функционал (к примеру, корзина товаров или процесс покупки) работал правильно и синхронизировался.

Если вы обнаружите и идентифицируете трафик/IP-адреса, которые должны быть заблокированы на вашем сайте, вы можете затем воспользоваться плагином безопасности WordPress. Однако не все хостинги позволяют устанавливать плагины безопасности. Kinsta, к примеру, запрещает, что сделано по нескольким причинам. Во-первых, такие плагины отражаются на производительности, особенно возможности сканирования. Во-вторых, функции блокировки IP в них не работают, поскольку хостинг использует балансировщики нагрузки с Google Cloud Platform.

Естественно, IP-адреса могут быть всегда заблокированы службой поддержки хостинга, однако, в зависимости от длительности и масштабов атаки, это может превратиться в бесконечный процесс. Многие атаки или спам при блокировке в одной области переключаются на другие зоны, меняют IP-адреса или прокси. Поэтому в данном случае мы рекомендуем установить решение безопасности, такое как Cloudflare или Sucuri.

  1. Проверьте ваши плагины и темы.

Многие считают, что сторонние плагины или темы не приводят к ошибкам 504 gateway timeout. И в большинстве случаев это верно. Но, по нашему опыту, медленный некэшируемый запрос от плагина может привести к задержкам, поскольку он задействует больше ваших PHP-воркеров. Как только вы достигнете предела PHP-воркеров, очередь будет убирать ваши прошлые запросы, что может вести к ошибкам 504. Их не следует путать с ошибками 502, когда ошибка появляется в результате достижения таймаута в 60 секунд в очереди.

Есть несколько способов устранения этой проблемы. Один из них — деактивация всех ваших плагинов. Помните, что вы не потеряете никаких своих данных, если отключите плагин. Если у вас есть доступ к панели администратора, просто перейдите к разделу с плагинами и выберите «Деактивировать» из меню с массовыми действиями. Это приведет к отключению всех ваших плагинов.

Если это устранило проблему, вам нужно найти ее виновника. Начинайте активировать плагин один за другим, перезагружая сайт после каждой активации. Как только вы увидите ошибку 504, вы сможете идентифицировать проблемный плагин. Затем вы можете обратиться к разработчику плагина за помощью или опубликовать тикет в репозитории WordPress.

Если у вас нет доступа к панели администратора, вы можете использовать FTP-клиент для подключения к своему серверу и переименования папки с плагинами в нечто вроде plugins_old. Затем проверьте свой сайт еще раз. Если это сработает, вам нужно будет протестировать каждый плагин по отдельности, чтобы найти виновника. Переименуйте папку с плагинами обратно в plugins и затем начинайте переименовывать папки отдельных плагинов внутри нее, пока не обнаружите проблемный плагин. То же самое можно сделать и на тестовом сайте.

Обязательно убедитесь в том, что все ваши плагины, темы и ядро WordPress обновлены до последней версии. И убедитесь, что вы используете поддерживаемую версию PHP.

Если плагин будет содержать плохой код, то вам, скорее всего, понадобится обратиться к разработчикам WordPress, чтобы решить эту проблему.

  1. Проверьте логи.

Вы также можете использовать ваши журналы (логи) ошибок. В Kinsta ошибки можно просмотреть в специальном разделе консоли MyKinsta. Вы сможете быстро установить проблему, особенно если ее источником является плагин на сайте. Если ваш хостинг не предлагает инструментов для ведения логов, вы можете добавить следующий код в файл wp-config.php, чтобы включить логгинг:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

Логи обычно расположены в каталоге /wp-content. Иногда они могут находиться в отдельных папках.

Вы можете также проверить логи в Apache и Nginx, которые чаще всего находятся по адресу:

Apache: /var/log/apache2/error.log

Nginx: /var/log/nginx/error.log

  1. Параметры Nginx

Если вы обслуживаете свой собственный сервер и WordPress сайты на Nginx + FastCGI (php-fpm) или Nginx как прокси для Apache, то в таком случае есть дополнительные настройки, которые вы можете изменить, чтобы предотвратить появление ошибок 504 gateway timeout.

Если вы используете Nginx с FastCGI (php-fpm), то в таком случае вам нужно сначала внести изменения в файл PHP-FPM. Перейдите в /etc/php5/fpm/pool.d/www.conf (может варьироваться в зависимости от версии PHP). Установите следующую директиву:

request_terminate_timeout = 300

Затем вы должны изменить файл php.ini, который обычно расположен по адресу /etc/php.ini. Найдите директиву max_execution_time. Увеличьте ее значение до 300 или создайте директиву, если ее нет:

max_execution_time = 300

Наконец, вам нужно будет изменить файл nginx.conf. Добавьте в конфигурацию вашего виртуального хоста Nginx следующее:

location ~ .php$ {

...

fastcgi_read_timeout 300;

}

Затем просто перезапустите Nginx и PHP-FPM.

service nginx reload

service php5-fpm reload

Если вы используете Nginx в качестве прокси для Apache, то в таком случае добавьте следующее в ваш файл nginx.conf:

proxy_connect_timeout 600;

proxy_send_timeout 600;

proxy_read_timeout 600;

send_timeout 600;

Далее просто перезапустите Nginx.

service nginx reload

Заключение

Как вы можете видеть, есть много разных способов и методов устранения ошибок 504 gateway timeout на WordPress сайте. Как правило, это проблемы с сервером, и в данном случае вам нужно связаться с вашим хостингом, чтобы решить их. Но важно помнить о том, что они могут также вызываться и сторонними плагинами или переполнением очереди/бэклога ваших PHP-воркеров.

Источник: kinsta.com

Stuck with Cloudflare error 504? We can help you.

Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.

This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.

It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.

Here at Bobcares, we often fix this error for our customers as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix this Cloudflare error for our customers.

What causes error 504 gateway timeout?

Some of the main causes for the Cloudflare 504 gateway timeout error is given below:

1. Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.

cloudflare error 504

2. 504 error originating from Cloudflare end.

cloudflare error 504

3. The 504 gateway timeout error at Cloudflare due to large uploads

How to fix Cloudflare error 504 gateway timeout

We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.

1. Fix for Receiving 504 from the origin web server 

We will ensure the below aspects at the webserver:

1. First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.

2. Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.

3. High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.

4.  Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.

2. Fix for 504 error originating from Cloudflare

At times error 504 will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.

However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.

For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:

1. The exact time and timezone when the issue occurred
2. URL that resulted in the HTTP 504 error as a response.

3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads

The reason for this is the size of the uploads to the site being too large causing server timeouts.

Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.

This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.

[Still, facing error? We are happy to help you!]

Conclusion

To conclude, we saw some of the common causes for the 504 error.  Also, we saw how our Support Engineers troubleshoot and fix Cloudflare 504 gateway timeout error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Содержание

  1. Cloudflare error 504 gateway timeout – How to fix
  2. What causes error 504 gateway timeout?
  3. How to fix Cloudflare error 504 gateway timeout
  4. 1. Fix for Receiving 504 from the origin web server
  5. 2. Fix for 504 error originating from Cloudflare
  6. 3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads
  7. Conclusion
  8. PREVENT YOUR SERVER FROM CRASHING!
  9. Как исправить ошибку 504 Gateway Timeout Error на WordPress сайте
  10. Почему появляется 504 Gateway Timeout Error?
  11. Варианты ошибки 504 Gateway Timeout Error
  12. Попробуйте перезагрузить страницу.
  13. Отключите параметры прокси.
  14. Проблемы с DNS.
  15. Временно отключите CDN
  16. Проблемы с сервером (проверьте ваш хост)
  17. Спам, боты и DDoS-атаки
  18. Проверьте ваши плагины и темы.
  19. Проверьте логи.
  20. Параметры Nginx
  21. Заключение

Cloudflare error 504 gateway timeout – How to fix

by Sushali Dasan | Jan 21, 2021

Stuck with Cloudflare error 504? We can help you.

Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.

This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.

It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.

Here at Bobcares, we often fix this error for our customers as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix this Cloudflare error for our customers.

What causes error 504 gateway timeout?

Some of the main causes for the Cloudflare 504 gateway timeout error is given below:

1. Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.

2. 504 error originating from Cloudflare end.

3. The 504 gateway timeout error at Cloudflare due to large uploads

How to fix Cloudflare error 504 gateway timeout

We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.

1. Fix for Receiving 504 from the origin web server

We will ensure the below aspects at the webserver:

1. First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.

2. Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.

3. High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.

4. Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.

2. Fix for 504 error originating from Cloudflare

At times error 504 will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.

However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.

For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:

1. The exact time and timezone when the issue occurred
2. URL that resulted in the HTTP 504 error as a response.

3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads

The reason for this is the size of the uploads to the site being too large causing server timeouts.

Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.

This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.

[Still, facing error? We are happy to help you!]

Conclusion

To conclude, we saw some of the common causes for the 504 error. Also, we saw how our Support Engineers troubleshoot and fix Cloudflare 504 gateway timeout error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

Как исправить ошибку 504 Gateway Timeout Error на WordPress сайте

Нет ничего более раздражающего, чем появление белого экрана с ошибкой при обращении к WordPress сайту. Некоторые из распространенных ошибок, с которыми вы могли сталкиваться ранее: белый экран смерти, ошибка установки соединения с базой данных и т.д. Для большинства блогов, а также сайтов, связанных с электронной коммерцией, появление таких ошибок приводит к потере дохода, поскольку посетители сразу покидают такой ресурс, а клиенты не могут совершить покупки. Сегодня мы рассмотрим ошибку 504 Gateway Timeout Error, а также дадим рекомендации по поводу того, как справиться с ней на своем WordPress сайте. Читайте далее о причинах этой ошибки и о том, как предотвратить ее появление.

Почему появляется 504 Gateway Timeout Error?

Перед тем, как мы рассмотрим саму ошибку, важно понять, из-за чего она появляется. Всякий раз, когда вы запускаете свой браузер и посещаете сайт, он передает запрос обратно на сервер, на котором размещен. Затем веб-сервер обрабатывает запрос и отправляет вам запрашиваемые ресурсы вместе с HTTP-заголовком. Этот заголовок содержит один из многочисленных кодов состояния HTTP, который позволяет понять, все ли в порядке или что-то пошло не так. Далеко не все коды состояния плохие. К примеру, код состояния 200 говорит о том, что все в порядке.

Существует много различных кодов ошибок 500 (500, 501, 502, 503, 504 и т.д.), которые имеют разное значение. Они указывают, что запрос был принят, но сервер не смог выполнить его.

В данном случае ошибка 504 означает, что «для сервера, работающего в качестве шлюза, вышло время ожидания ответа от другого сервера». Код возвращается, когда есть два сервера, участвующих в обработке запроса, и время ожидания ответа от второго сервера со стороны первого сервера истекло (RFC 7231, раздел 6.6.5).

Варианты ошибки 504 Gateway Timeout Error

Вследствие многообразия веб-браузеров, операционных систем и серверов ошибка 504 может быть представлена разными способами. Все они, как правило, несут в себе одно и то значение. Ниже приведены некоторые из вариантов, с которыми вы можете столкнуться:

  • “504 Gateway Timeout”
  • “504 Gateway Timeout NGINX”
  • “NGINX 504 Gateway Timeout”
  • “Gateway Timeout Error”
  • “Error 504”
  • “HTTP Error 504”
  • “HTTP Error 504 – Gateway Timeout”
  • “HTTP 504”
  • “504 Error”
  • “Gateway Timeout (504)
  • “504 Gateway Time-out – The server didn’t respond in time”

Как справиться с ошибкой 504 Gateway Timeout Error

С чего следует начать решение проблем, если вы столкнулись с ошибкой 504 Gateway Timeout Error на своем WordPress сайте? Не имея контекста, достаточно сложно понять, что делать в первую очередь. Как правило, ошибку вызывают проблемы с сетевым подключением и проблемы с сервером, на котором расположен сайт. Однако ошибка может быть следствием проблем на стороне клиента или даже результатом использования стороннего плагина. Мы немного углубимся в этот вопрос. Давайте ознакомимся с популярными причинами появления ошибки, а также рассмотрим то, как исправить ее.

Попробуйте перезагрузить страницу.

Одна из первых вещей, которую вы должны сделать, столкнувшись с ошибкой 504 Gateway Timeout Error – это просто подождать минуту и перезагрузить страницу. Возможно, хостинг или сервер просто перегружен, и сайт быстро вернется в работу. Вы можете также попробовать другой браузер.

Еще одна вещь, которую вы можете сделать – это проверить статус вашего сайта на downforeveryoneorjustme.com. Этот сайт подскажет вам, вышел ли сайт из строя только у вас или же у всех посетителей. Инструмент проверяет код состояния HTTP, который возвращается сервером. Если код отличается от 200, то в таком случае вы увидите указатель Down (т.е. сайт «лежит» для всех).

Отключите параметры прокси.

Иногда вы можете столкнуться с ошибкой 504, если вы используете прокси-сервис. Эти случаи являются очень редкими, особенно на стороне клиента. Однако иногда такие настройки могут быть установлены без ведома клиента. В сети есть руководства, посвященные отключению настроек прокси на Windows и Mac.

Проблемы с DNS.

Ошибка 504 gateway timeout может быть вызвана проблемами с DNS. Такая ошибка может возникать с двух сторон. На стороне сервера она происходит, к примеру, когда домен не преобразован в корректный IP. Если вы только что перенесли свой сайт WordPress на новый хостинг, то важно дождаться распространения DNS. Обычно это занимает до 24 часов. Все зависит от значения TTL ваших DNS-записей. Вы можете использовать бесплатный инструмент, такой как DNSMap, чтобы проверить, распространились ли ваши DNS по всему миру.

Вторая проблема с DNS связана уже с клиентской стороной. В этом случае вы можете очистить свой локальный DNS кэш. Это похоже на очистку кэша браузера.

В Windows просто откройте командную строку и введите следующее:

Вы должны увидеть сообщение «Successfully flushed the DNS resolver Cache».

В macOS введите следующее в терминал:

Примечание: на Mac нет сообщений об успешном завершении.

И, наконец, вы можете временно изменить ваши клиентские DNS-серверы. По умолчанию DNS-серверы автоматически привязываются вашим интернет-провайдером. Вы можете временно сменить их на публичный DNS-сервер, такой как Google. Некоторые предпочитают постоянно использовать публичные DNS Google, поскольку они в некоторых случаях могут быть более надежными.

Временно отключите CDN

Также проблема может связана с CDN (сетью доставки контента). Если вы используете стороннего CDN провайдера, вы можете просто временно отключить ваш CDN. К примеру, нам нравится бесплатный плагин CDN Enabler. Если вы используете его, вы можете просто отключить плагин, чтобы проверить работу сайта. Перестали попадать в консоль WordPress после этого? В таком случае войдите на сайт через SFTP и переименуйте папку с плагином в cdn-enabler_old. В итоге ваше CDN соединение будет временно отключено. То же самое касается плагина WP Rocket или любого другого плагина, который подцеплялся к CDN.

Иногда эта ошибка может быть следствием использования прокси-сервисов, таких как Cloudflare или Sucuri, поскольку у них есть дополнительные файрволы. Большинство из них кэшируют коды состояния 500, когда они возвращаются вашим исходным сервером. Мы заметили, что это время от времени происходит на бесплатном тарифе Cloudflare. К сожалению, поскольку Cloudflare является полным прокси-сервисом, быстрого способа его отключения не существует.

Однако, прежде чем грешить на Cloudflare, важно знать, что есть два типа ошибки 504:

504 Gateway Timeout в Cloudflare (вариант 1)

Если вы видите следующую страницу, то в данном случае проблема на стороне Cloudflare. Обратитесь к ним в поддержку. Либо проверьте их страницу со статусом. Скорее всего, они уже уведомлены о данной проблеме и работают над ней.

504 Gateway Timeout в Cloudflare (вариант 2)

Если вы видите следующую страницу, то это проблема с вашим хостом WordPress (исходный сервер), и в этом случае вам нужно воспользоваться рекомендацией под номером 5.

Проблемы с сервером (проверьте ваш хост)

Проблемы с сервером – одна из распространенных причин, почему пользователи сталкиваются с ошибками 504 на своих WordPress-сайтах. Говоря простым языком, Nginx или Apache ожидают ответа от второй стороны, и время ожидания истекло.

Ошибки 504 чаще всего встречаются на сайтах с высоким трафиком и на сайтах электронной коммерции (с установленным WooCommerce, к примеру), у которых много некэшируемых запросов. Это может вызывать перегрузку сервера. Однако мы сталкивались с такими ошибками на разных типах сайтов, в том числе и на обычных блогах. Многие хостинги отвечают стандартными фразами по типу «вам нужно перейти на более дорогостоящий тарифный план, чтобы исправить эту проблему». И пусть это обычно помогает решить данную проблему, зачастую это не является необходимым.

Хостинги, такие как, к примеру, Kinsta, используют контейнеры LXD для каждого сайта. Это означает, что каждый сайт размещается в своем изолированном контейнере, в котором имеются все необходимые программные ресурсы, требуемые для его запуска (Linux, Nginx, PHP, MySQL). Ресурсы на 100% конфиденциальны и не делятся ни с кем. Многие виртуальные хостинги WordPress не имеют данной возможности, поэтому любой соседний сайт с высоким трафиком будет вызывать ошибки 504 на вашем сайте.

В Kinsta инфраструктура построена так, чтобы легко обрабатывать тысячи одновременных подключений. Даже базы данных MySQL размещаются на локальном хосте, а не на удаленном сервере. Это гарантирует отсутствие задержки между машинами, что приводит к более быстрым запросам и меньшей вероятности возникновения тайм-аута между ними.

Помимо тайм-аутов сервера из-за повышенной нагрузки есть и другие причины, в результате чего может возникнуть ошибка 504:

  • Медленный сервер. Вполне возможно, что сервер, на котором расположен ваш WordPress сайт, слишком медленно отвечает на запросы, и поэтому он генерирует ошибки шлюза.
  • Недостаточно PHP воркеров. PHP-воркеры используются для выполнения кода на вашем WordPress-сайте. На требовательных в плане ресурсов сайтах вполне может быть так, что все PHP-воркеры заняты, и в этом случае они начинают формировать очередь. Если очередь и бэклог заполнены, старые запросы начинают игнорироваться. Вы можете попросить ваш хостинг увеличить количество PHP-воркеров. Дополнительные PHP-воркеры для сайта позволяют одновременно выполнять несколько запросов.
  • Проблемы с файрволом. Файрвол на вашем сервере может содержать ошибки в результате неверной конфигурации или правил, препятствующих установлению соединения.
  • Сетевое подключение. Если возникают проблемы с сетевым подключением между прокси-сервером и веб-сервером, то это может вести к задержкам с ответом для HTTP-запросов. Также могут возникать сетевые проблемы с балансировщиком нагрузки, если он используется.

Также важно отметить, что ошибки 504 могут обманчиво выглядеть как ошибки 503 (сервис недоступен) или даже ошибки 502 (bad gateway), но на практике они отличаются.

Если вы хотите предотвратить появление таких ошибок в будущем, вы можете воспользоваться инструментом, таким как updown.io, для отслеживания ситуации и немедленного уведомления о любых проблемах. Сервис периодически отправляет HTTP HEAD-запрос к указанному URL. Вы можете просто задать вашу главную страницу. Можно задавать частоту проверок:

Он пришлет вам электронное письмо, если ваш сайт перестал работать, с указанием времени, когда это случилось. Ниже приведен пример:

Это может быть особенно полезно, если вы используете виртуальный хостинг, который, как правило, работает на пределе возможностей. Это даст вам доказательство того, что ваш сайт не работал (к примеру, ночью). По этой причине мы и советуем переходить к администрируемым (управляемым) хостингам.

Спам, боты и DDoS-атаки

Может быть так, что ваш сайт был заспамлен ботами или подвержен DDoS-атаке. Иногда это ведет к некэшируемым запросам и, как следствие, к перегрузке сервера, что и выливается в ошибку 504 gateway timeout. Вы можете изучить аналитику сервера, чтобы увидеть, есть ли в ней какие-либо паттерны. В Kinsta имеется, к примеру, инструмент MyKinsta для аналитики. Вы можете попросить эти данные у вашего хостинга.

Первый отчет, который мы советуем изучить – это IP-адреса топовых клиентов. Обычно это очень полезно, особенно если ваш сайт внезапно стал генерировать большой трафик или попал под атаку ботов.

Второй отчет, который мы рекомендуем посмотреть – это запросы и боты. Вы можете быстро сравнить количество людей, попадающих на ваш сайт, с количеством ботов и роботов. Однако помните, что не все боты плохие. GoogleBot – пример хорошего бота, он сканирует сайт для индексации содержимого в результатах поиска.

Третий отчет, который мы рекомендуем посмотреть – это анализ кэша. Здесь вы можете видеть, какие запросы отсутствуют в кэше, а также каковы топовые локации вашего сайта. По причинам производительности и стабильности вы должны стараться закэшировать как можно больше запросов. Это не всегда возможно, поскольку некоторые сайты генерируют большое количество некэшируемых запросов (как в случае с WooCommerce), и они нужны для того, чтобы функционал (к примеру, корзина товаров или процесс покупки) работал правильно и синхронизировался.

Если вы обнаружите и идентифицируете трафик/IP-адреса, которые должны быть заблокированы на вашем сайте, вы можете затем воспользоваться плагином безопасности WordPress. Однако не все хостинги позволяют устанавливать плагины безопасности. Kinsta, к примеру, запрещает, что сделано по нескольким причинам. Во-первых, такие плагины отражаются на производительности, особенно возможности сканирования. Во-вторых, функции блокировки IP в них не работают, поскольку хостинг использует балансировщики нагрузки с Google Cloud Platform.

Естественно, IP-адреса могут быть всегда заблокированы службой поддержки хостинга, однако, в зависимости от длительности и масштабов атаки, это может превратиться в бесконечный процесс. Многие атаки или спам при блокировке в одной области переключаются на другие зоны, меняют IP-адреса или прокси. Поэтому в данном случае мы рекомендуем установить решение безопасности, такое как Cloudflare или Sucuri.

Проверьте ваши плагины и темы.

Многие считают, что сторонние плагины или темы не приводят к ошибкам 504 gateway timeout. И в большинстве случаев это верно. Но, по нашему опыту, медленный некэшируемый запрос от плагина может привести к задержкам, поскольку он задействует больше ваших PHP-воркеров. Как только вы достигнете предела PHP-воркеров, очередь будет убирать ваши прошлые запросы, что может вести к ошибкам 504. Их не следует путать с ошибками 502, когда ошибка появляется в результате достижения таймаута в 60 секунд в очереди.

Есть несколько способов устранения этой проблемы. Один из них — деактивация всех ваших плагинов. Помните, что вы не потеряете никаких своих данных, если отключите плагин. Если у вас есть доступ к панели администратора, просто перейдите к разделу с плагинами и выберите «Деактивировать» из меню с массовыми действиями. Это приведет к отключению всех ваших плагинов.

Если это устранило проблему, вам нужно найти ее виновника. Начинайте активировать плагин один за другим, перезагружая сайт после каждой активации. Как только вы увидите ошибку 504, вы сможете идентифицировать проблемный плагин. Затем вы можете обратиться к разработчику плагина за помощью или опубликовать тикет в репозитории WordPress.

Если у вас нет доступа к панели администратора, вы можете использовать FTP-клиент для подключения к своему серверу и переименования папки с плагинами в нечто вроде plugins_old. Затем проверьте свой сайт еще раз. Если это сработает, вам нужно будет протестировать каждый плагин по отдельности, чтобы найти виновника. Переименуйте папку с плагинами обратно в plugins и затем начинайте переименовывать папки отдельных плагинов внутри нее, пока не обнаружите проблемный плагин. То же самое можно сделать и на тестовом сайте.

Обязательно убедитесь в том, что все ваши плагины, темы и ядро WordPress обновлены до последней версии. И убедитесь, что вы используете поддерживаемую версию PHP.

Если плагин будет содержать плохой код, то вам, скорее всего, понадобится обратиться к разработчикам WordPress, чтобы решить эту проблему.

Проверьте логи.

Вы также можете использовать ваши журналы (логи) ошибок. В Kinsta ошибки можно просмотреть в специальном разделе консоли MyKinsta. Вы сможете быстро установить проблему, особенно если ее источником является плагин на сайте. Если ваш хостинг не предлагает инструментов для ведения логов, вы можете добавить следующий код в файл wp-config.php, чтобы включить логгинг:

Логи обычно расположены в каталоге /wp-content. Иногда они могут находиться в отдельных папках.

Вы можете также проверить логи в Apache и Nginx, которые чаще всего находятся по адресу:

Параметры Nginx

Если вы обслуживаете свой собственный сервер и WordPress сайты на Nginx + FastCGI (php-fpm) или Nginx как прокси для Apache, то в таком случае есть дополнительные настройки, которые вы можете изменить, чтобы предотвратить появление ошибок 504 gateway timeout.

Если вы используете Nginx с FastCGI (php-fpm), то в таком случае вам нужно сначала внести изменения в файл PHP-FPM. Перейдите в /etc/php5/fpm/pool.d/www.conf (может варьироваться в зависимости от версии PHP). Установите следующую директиву:

Затем вы должны изменить файл php.ini, который обычно расположен по адресу /etc/php.ini. Найдите директиву max_execution_time. Увеличьте ее значение до 300 или создайте директиву, если ее нет:

Наконец, вам нужно будет изменить файл nginx.conf. Добавьте в конфигурацию вашего виртуального хоста Nginx следующее:

Затем просто перезапустите Nginx и PHP-FPM.

Если вы используете Nginx в качестве прокси для Apache, то в таком случае добавьте следующее в ваш файл nginx.conf:

Далее просто перезапустите Nginx.

Заключение

Как вы можете видеть, есть много разных способов и методов устранения ошибок 504 gateway timeout на WordPress сайте. Как правило, это проблемы с сервером, и в данном случае вам нужно связаться с вашим хостингом, чтобы решить их. Но важно помнить о том, что они могут также вызываться и сторонними плагинами или переполнением очереди/бэклога ваших PHP-воркеров.

Источник

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. For many WordPress blogs and ecommerce platforms, knowing how to fix server errors like this is crucial to keep their hard-earned visitors from bouncing to competitor sites.

As the 504 Gateway Timeout error doesn’t tell you why it occurred, it’s hard to pinpoint what’s causing the server timeout. This article will help you understand it in detail, learn how to diagnose its cause, and then fix it.

After trying all the various solutions mentioned in the post, your site should be up and running in no time.

Sounds interesting? Let’s dive in!

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. 🤔 Learn how to fix it with this guide quickly. ⬇️Click to Tweet

Prefer to watch the video version?

What Is the 504 Gateway Timeout Error?

Every time you visit a website in your browser, the browser sends a request to the web server where the site is hosted. The server processes the request and responds with the requested resources.

Illustration of how HTTP requests and responses work

How HTTP requests and responses work.

The server response includes one of many HTTP status codes to indicate the response’s status to the browser. But not all these HTTP status codes are errors. For instance, a 200 OK status code means that the server processed the request successfully and “Everything is OK.”

The 5xx class of HTTP status codes indicates that something’s wrong with the server, the server is aware of it, and it cannot carry out the client request. As a result, they’re also referred to as Server Error 5xx status codes.

Officially, five status codes are specified under the 5xx class (500, 501, 502, 503, 504). You may come upon many unofficial codes too (506, 507, 509, 520, etc.).

The Internet Engineering Task Force (IETF) defines the 504 Gateway Timeout error as:

The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.

To simplify it further, this error occurs when two servers are involved in processing a request. The first server (typically the main server) times out, waiting for a response from the second server (upstream server).

The 504 Gateway Timeout error manifests itself in various forms. Here are some ways it usually shows up:

The HTTP ERROR 504 in Chrome browser

The ‘HTTP ERROR 504’ in the Chrome browser.

The 504 Gateway Timeout error is similar to the 502 Bad Gateway error, which indicates that the first server received an invalid response from the second server (upstream server).

504 GATEWAY TIMEOUT status code in Chrome DevTools

The ‘504 GATEWAY TIMEOUT’ status code in Chrome DevTools.

Variations of the 504 Gateway Timeout Error

The browser displays any 504 Gateway Timeout error inside it, just like any other error. As there are various operating systems, web servers, browsers, and user agents, it can show up in multiple ways.

Below are a few common 504 error message variations that you may run into:

  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • Gateway Timeout Error
  • Error 504
  • HTTP Error 504
  • HTTP Error 504 — Gateway Timeout
  • HTTP 504
  • 504 Error
  • Gateway Timeout (504)
  • This page isn’t working — Domain took too long to respond
  • 504 Gateway Time-out — The server didn’t respond in time
  • The page request was canceled because it took too long to complete
  • Site visitors: There was an issue serving your request, please try again in a few minutes.
  • Site Owners: There was a gateway timeout. You should visit your error log for more information.
  • A blank white screen

All the above error responses, though worded differently, point to the same 504 Gateway Timeout server error.

Web servers and websites can customize how they show the 504 Gateway Timeout error to users. Some of them can be cool! It’s an excellent tactic to quell their visitors’ disappointment.

GitHub’s customized HTTP 504 error page

GitHub’s customized HTTP 504 error page.

SEO Impact of the 504 Gateway Timeout Error

All 5xx errors prevent a webpage from loading, making them detrimental to user experience. Hence, search engines like Google take these errors seriously. If the error persists for a long duration, it may even lead to deindexing the webpage from the search engine results.

For example, when Google spiders stumble upon a 503 Service Unavailable error, they’ll understand that it’s a temporary issue as it’s mostly used to enable site maintenance mode. Thus, they’ll try to crawl the page again later.

A 504 Gateway Timeout error isn’t necessarily temporary as it can be due to multiple reasons. If your site is down for just a few minutes, and if the spiders are trying to crawl it multiple times every minute, they’ll try to serve the page from their cache.  They wouldn’t even notice it.

But if your site is down for 6+ hours or more, then Google will consider the 504 error as a serious site-wide issue that you need to fix as soon as possible. This can impact your SEO negatively.

Viewing the crawl errors in Google Search Console

Viewing the crawl errors in Google Search Console

Google Search Console is one of the best SEO tools to monitor your website’s HTTP 5xx errors.

Causes of the 504 Gateway Timeout Error

As the 504 error is due to a timeout between servers, the problem probably isn’t with the client’s device or internet connection. That also includes your device and connection.

A 504 Gateway Timeout error indicates that the web server is waiting too long to respond from another server and “timing out.” There can be many reasons for this timeout: the other server is not functioning properly, overloaded, or down.

The other server need not always be external (e.g. CDN, API gateway). It can also be a server-like entity within the main web server (e.g. reverse proxy server, database server).

How to Fix the 504 Gateway Timeout Error

Without knowing exact details about the site, such as its server configuration, hosting plan, third-party plugins, and the traffic it attracts, you may find it frustrating and overwhelming to fix a 504 Gateway Timeout error.

Since many variables are involved, I recommend you to start by fixing client-side issues, which are pretty rare, and then move towards fixing server-side problems. They’re usually the culprits with 504 errors.

  1. Try Reloading the Webpage
  2. Reboot Your Network Devices
  3. Check Your Proxy Settings
  4. Check for DNS Issues
  5. Disable Your Site’s CDN Temporarily
  6. Check Server Issues With Your Host
  7. Check for Spam, Bots, or DDoS Attacks
  8. Repair Your Corrupted WordPress Database
  9. Check Your Site’s Plugins and Themes
  10. Check Error Logs
  11. Configure Apache or Nginx Settings Properly

1. Try Reloading the Webpage

One of the first things you can try when encountering a 504 Gateway Timeout error is to wait a few minutes and try reloading the page.

You can press the F5 keyboard shortcut to refresh/reload the webpage in most browsers. To remove the page’s browser cache before reloading, you can press the CTRL+F5 shortcut combo instead.

Refreshing a webpage in Chrome browser

Refreshing a webpage in Chrome browser

While you’re at it, you can also try loading the site in a different browser to rule that out as an issue. As most 504 errors are due to temporarily overloaded servers, using this solution should make your site come right back.

If waiting and reloading the site doesn’t fix the 504 error issue, you can check whether a site is down for everyone or just you. Two useful online tools to test a site for downtime are Down for Everyone or Just Me and Is It Down Right Now?

Testing Kinsta.com on Down for Everyone or Just Me

Testing Kinsta.com on Down for Everyone or Just Me

2. Reboot Your Network Devices

Sometimes, problems with your network devices like modem or router could lead to a 504 Gateway Timeout error. Rebooting these devices could help you with fixing the problem.

While you can switch off all these networking devices in any order, the order you switch them back on is important. Typically, turn these devices on from the “outside-in,” following the connection order from the internet service provider to your main client device.

3. Check Your Proxy Settings

A proxy server sits between your device and the internet. It’s mostly used to enhance online privacy by hiding private information (e.g. device location) from websites and webservers (e.g. using a VPN).

While it’s rare for proxy servers to cause a 504 error, incorrect proxy server settings can sometimes be the reason. You can disable the proxy server and try reloading the webpage to see whether it’ll fix the error.

Changing the ‘Proxy’ settings in Windows 10

Changing the ‘Proxy’ settings in Windows 10

Most clients don’t use a proxy service, so you can skip this step if you’re confident that you don’t use any proxy server. However, you might have set it without you even knowing about it. I’d suggest you check your device’s and browser’s proxy settings to rule this cause out.

4. Check for DNS Issues

A 504 Gateway Timeout error can also be caused by DNS issues on the server-side or the client-side (or both).

The most probable reason for a server-side DNS issue is the FQDN (fully qualified domain name) not resolving the correct IP address or the DNS server not responding. Usually, this occurs when you’ve just migrated your site to a new server or host. Hence, it’s important to wait for the domain’s DNS records to propagate fully, which can take up to 24 hours.

You can use free tools like whatsmydns.net DNS Checker or DNSMap to see if your DNS has propagated around the globe.

Checking DNS propagation for your domain on whatsmydns.net

Checking DNS propagation for your domain on whatsmydns.net

For fixing client-side DNS issues, you could try flushing your local DNS cache. It’s like clearing your browser cache, except here, you’re flushing the DNS cache from the operating system.

If you’re using Windows, you can flush the DNS cache by opening the Command Prompt and entering the following directive:

ipconfig /flushdns

Flushing the DNS Cache with Command Prompt

Flushing the DNS Cache with Command Prompt in Windows

You should see a “Successfully flushed the DNS resolver Cache.” message if it worked.

For the latest macOS versions, you can open the Terminal and run the following command:

sudo killall -HUP mDNSResponder

You won’t see any notification in macOS when the process finishes, but you can change that by appending the command with your custom message.

sudo killall -HUP mDNSResponder; DNS Cache was cleared successfully

If you’re using older macOS versions, the command you need to enter varies based on which version of macOS you’re running. For more details, you can refer to the macOS section in Kinsta’s in-depth flush DNS tutorial.

If you’re using the Linux operating system, then the process is quite similar to macOS as even Linux uses the Terminal as its command-line interface. Since there are many Linux distributions, the exact command you need to run may vary from one distro to another. You can check out Kinsta’s guide for more information.

Finally, you can change your client-side DNS servers temporarily. By default, your ISP assigns the DNS servers automatically to you. But you can change these to public DNS IPs temporarily.

Some reliable DNS servers you can try out are Google Public DNS, Cloudflare 1.1.1.1, Quad9 DNS, and Cisco OpenDNS.

Settings custom DNS servers in Windows 10

Settings custom DNS servers in Windows 10

5. Disable Your Site’s CDN Temporarily

Sometimes, the issue could also be with your content delivery network (CDN). If a site’s origin server isn’t reachable, most CDNs will try to serve the full webpage from their cache.

But most CDNs don’t enable this feature by default as it’s complex to cache dynamic assets on most sites (e.g. the WordPress admin dashboard).

Setting the ‘Cache Everything’ page rule in Cloudflare

Setting the ‘Cache Everything’ page rule in Cloudflare

A straightforward way to troubleshoot this is to disable your CDN temporarily. For example, if you’re using the free CDN Enabler WordPress plugin to link your site assets to the CDN URLs, then you can deactivate the plugin and test reloading your site.

The same goes for using any other plugin you may use to connect to your CDN (e.g. WP Rocket, Breeze, W3 Total Cache).

If you can’t access your site’s admin dashboard, you can disable the plugin via SFTP by renaming the plugin’s folder name.

Disable all plugins via SFTP by renaming the plugins folder name

Disable all plugins via SFTP by renaming the plugins folder name

CDNs like Cloudflare or Sucuri, which provide full proxy services, have extra firewalls between their edge servers and your origin server. Hence, you may encounter HTTP 5xx errors more frequently while using them. Most of them cache 5xx errors returned by your origin server, so it’s easy to troubleshoot them.

Cloudflare’s free plan is prone to throw up a 5xx error. Unfortunately, since it’s a full proxy service, there’s no quick way to disable it. But before you blame Cloudflare for it, know that Cloudflare shows two variations of the 504 Gateway Timeout error.

504 Gateway Timeout at Cloudflare (Variation 1)

Cloudflare will show you a custom 504 Gateway Timeout error screen when your site’s origin server responds with a standard HTTP 504 response.

Cloudflare’s custom Error 504 screen

Cloudflare’s custom Error 504 screen

Here, the issue lies with your web server and not Cloudflare. You can try fixing it with the other solutions mentioned below or contact your hosting provider’s support for technical help.

504 Gateway Timeout at Cloudflare (Variation 2)

If Cloudflare causes the 504 Gateway Timeout error, the error screen will mention “cloudflare,” which is currently the standard server name for all Cloudflare assets. Usually, the error screen will appear as below:

504 Gateway Timeout error caused by Cloudflare

Error screen for 504 Gateway Timeout caused by Cloudflare

Since Cloudflare itself is unresponsive, you’ll not see any Cloudflare-branded error screen here.

Most likely, Cloudflare is already aware of the issue and is working on a fix already. You can confirm this by checking the Cloudflare System Status webpage. Alternatively, you can get in touch with Cloudflare support for a quicker resolution.

Check Cloudflare System Status at cloudflarestatus.com

Check Cloudflare System Status at cloudflarestatus.com

504 Gateway Timeout at Cloudflare Due to Large Uploads

The size of your uploads to your site can also be a reason for the server timeouts. Cloudflare limits upload file size (per HTTP POST request) to just 100 MB on both Free and Pro plans.

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

The issue can be on your host’s end or with Cloudflare. You can find out the exact cause by bypassing Cloudflare with your DNS hosts file and trying your upload again.

If you’re using Cloudflare with WordPress, I recommend using their free plugin and excluding critical URLs from caching (such as the WordPress admin dashboard). You can refer to Kinsta’s detailed post on how to configure Cloudflare settings for WordPress.

Suggested reading: How to Set up Cloudflare APO for WordPress.

6. Check Server Issues With Your Host

Server issues are one of the most common reasons for facing a 504 Gateway Timeout error. Since most WordPress sites are hosted on Nginx or Apache webservers, Nginx or Apache is waiting for a response from something and timing out.

Many clients come to Kinsta for exactly this problem they’re facing at other hosts. The conversation goes something like this:

We’re getting around 100k visitors per month with more than 200k views. Currently, we’re hosting with ____ and we experience 504 errors constantly due to server overload. I don’t like how ____ handled the problem, and we were also advised that we will have to move to their dedicated plans soon, which I believe is not necessary.

High-traffic and ecommerce sites are more prone to getting 504 errors because of server overload as they generate many uncacheable requests. However, this issue can crop with any site, including simple blogs. Many hosts will ask you to upgrade to a high-tier plan to fix the issue, which in most cases is unnecessary.

Kinsta uses LXD managed hosts and orchestrated LXC software containers for each site. Thus, every site is housed in its own isolated container with access to all the software required to run it (Linux, Nginx, PHP, MySQL). The resources are 100% private and aren’t shared with any other site, even your sites.

Most hosts providing shared hosting plans don’t have this capability. Hence, a high-traffic site hosted on the same server as yours may cause your site to throw up a 504 error too.

Apart from isolating each site in its container, Kinsta has also designed its infrastructure to handle thousands of concurrent connections easily. Kinsta even hosts the MySQL databases at localhost, not a remote server. This means no latency between machines, resulting in faster queries and fewer chances of timeouts occurring.

Many clients who migrate to Kinsta see huge decreases in overall load times.

A 212.5% increase in performance after switching to C2.

A 212.5% increase in performance after switching to C2.

An overloaded server isn’t the only cause for a server timeout. There can be many other reasons for the 504 error:

Slow Server Infrastructure

The server you use to host your site may not have enough resources to handle the load. It’s like playing a modern, graphics-intensive videogame on a decade-old PC.

The server just hangs up trying to serve the website. The only solution to this problem is to upgrade to a server with better infrastructure. For this reason, even Kinsta’s most basic hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic. If all the server’s PHP workers are busy, they’ll build up a queue.

When the queue gets too big, the server disregards old requests, which may cause the server to throw up a 504 gateway error. You can ask your host about increasing your number of PHP workers. This’ll allow your site to execute multiple requests simultaneously.

Firewall Issues

Your server’s firewall could have some errors or an improper configuration. Perhaps, a few of its rules prevent the server from establishing a connection properly. To know if your firewall is the culprit, you can check your server’s error logs.

Network Connectivity Problems

Connectivity issues between the proxy server and the web server could cause delays in responding to HTTP requests. If you use a load balancer, there could also be network connectivity issues with it.

HTTP Timeouts

HTTP timeouts can occur when a connection between the web server and the client is kept open for too long. With WordPress sites, this usually happens when running WordPress imports. One way to resolve this issue is to switch to a faster internet connection.

You can also use a tool with support for WP-CLI to run the scripts directly on the server, bypassing the HTTP connection entirely. For instance, you can use the wp import WP-CLI command to run the WordPress Importer plugin directly through the command-line interface.

Important: 504 Gateway Timeout errors look similar to 503 Service Unavailable errors or 502 Bad Gateway errors. But they’re all different. If you’re experiencing a 504 error at Kinsta, open a support ticket to get your issue fixed immediately.

For monitoring your site’s downtime on your own, you can use a tool like updown.io. It’ll check your website’s status (or any URL) periodically by sending an HTTP request to it. You can set the check frequency from 15 seconds to 1 hour. If your website isn’t responding correctly, it’ll notify you with an email or an SMS.

Monitor your website with updown.io

Monitor your website easily with updown.io

You’ll get a generous quantity of free credits with every account of updown.io, but if you’re looking for cheaper alternatives, you can check out WebGazer or UptimeRobot. Both these tools will help you monitor your site’s uptime every 5 minutes for free. That’s decent enough for most website owners.

WebGazer website monitoring tool's dashboard

WebGazer website monitoring tool’s dashboard

Monitoring your website will give you an idea of how often it’s down. This is especially helpful if you’re using a shared hosting provider. Most application, database, and managed WordPress hosts (like Kinsta) take care of this automatically for you. Hence it’s always recommended to go with them.

For a detailed explanation, check out Kinsta’s post on the importance of managed WordPress hosting.

7. Check for Spam, Bots, or DDoS Attacks

Malicious attackers can bring your web server to a crawl by sending too many and/or resource-intensive requests. If your site is getting spammed by bots or undergoing a DDoS attack, it can overwhelm your server and result in 504 Gateway Timeout errors for many genuine users.

You can look at your server traffic and analytics to see if you can spot any irregular patterns in the site traffic. If you’re using Kinsta to host your site, you can view this data easily by going to your MyKinsta Analytics dashboard.

MyKinsta Analytics dashboard

MyKinsta Analytics dashboard

Start your investigation by looking at the top client IPs. It’ll give you an idea of who generates the maximum number of requests, and from where. If your server suddenly uses up enormous bandwidth or attracts a lot of traffic, then this report will come in super handy.

Viewing ‘Top Client IPs’ in MyKinsta dashboard

Viewing ‘Top Client IPs’ in MyKinsta dashboard

Next, you can check out the Cache Analysis report. Here, you can see how many requests are bypassing or missing the cache, or being served from the cache. For performance and stability reasons, you want to cache as many requests as possible, but it’s not always possible to achieve that.

For example, WooCommerce sites generate many uncacheable requests for features such as the shopping cart and the checkout process.

The ‘Cache Analysis’ screen in MyKinsta

The ‘Cache Analysis’ screen in MyKinsta

Finally, you can use a security plugin to beef up your website’s security by spotting and blocking worrisome traffic/IPs. You can ask your host to block certain IPs too.

Depending upon the length and scale of the attack, this could be a never-ending process of blacklisting IPs as many attackers change their IPs and proxy addresses after getting blocked.

Note: Kinsta doesn’t allow its clients to install security plugins as they can have a huge effect on the site’s performance, especially its scanning capabilities. As Kinsta uses load balancers with Google Cloud Platform, blocking IPs wouldn’t always work as intended.

You can use dedicated security solutions such as Cloudflare or Sucuri to protect your sites from DDoS attacks and spambots. For more, you can check out Kinsta’s articles on how to install Cloudflare on your site and how Sucuri helped stop a DDoS attack in its tracks.

8. Repair Your Corrupted WordPress Database

Sometimes, a 504 Gateway Timeout error can be because of a corrupt database, especially in WordPress sites. Typically, this is due to corrupted database tables or files. Sometimes, it can also be caused by a serious security issue like your site or database being hacked.

Repairing a corrupted WordPress database depends on the problem. Plugins like WP-DBManager make it easy to diagnose database issues and repair them. I recommend you to read Kinsta’s detailed walkthrough on repairing WordPress database issues to get started.

9. Check Your Site’s Plugins and Themes

In most cases, third-party plugins and themes don’t cause 504 errors. But there’s a slight chance that they might cause server timeouts, usually by queuing up many uncached requests generated by the plugin/theme. As this ties up a lot of your server’s PHP workers, it can cause 504 errors.

A great example of this issue is WooCommerce, a plugin installed to add ecommerce functionality to WordPress sites.

The simplest way you can troubleshoot this problem is by deactivating all your plugins. Remember, you won’t lose any data if you just deactivate a plugin.

If you can access your admin dashboard, you can go to the Plugins screen, select Deactivate from the bulk actions menu, checkmark all the plugins, and then hit the Apply button. This will disable all of your plugins.

Deactivate plugins in WordPress

Deactivating all the WordPress plugins through WP admin dashboard

If you can’t access your admin area, you can disable plugins via SFTP using the method described before. Just rename the main plugin folder name to disable all the plugins in bulk.

Once you’ve deactivated all the plugins, check whether your site loads properly. If it works, you must activate each plugin, testing the site after enabling every plugin.

Finally, make sure that your plugins, themes, and WordPress core are up to date. Also, ensure that your server is running the recommended version of PHP.

If you feel this to be too overwhelming, you can always reach out to your host for help. Kinsta uses Kinsta APM and other troubleshooting techniques to help clients narrow down what plugin, query, or script might cause the error.

In the worst-case scenarios, like an inefficient query or bad code in a plugin/theme, you can bring in a WordPress developer to fix the issue.

10. Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your site. This can help you narrow down an issue on your site quickly, especially if it’s resulting from a demanding plugin on your site.

If you’re a Kinsta customer, you can easily see errors in the log viewer in your MyKinsta dashboard.

Checking error logs inside MyKinsta dashboard

Checking error logs inside the MyKinsta dashboard

If your host doesn’t have a logging tool, then you can enable WordPress debug mode by adding the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

The WP_DEBUG constant enables or disables the WordPress debug mode. It has two optional companion constants that can extend its features. The WP_DEBUG_LOG constant directs all errors to be saved to a debug.log file within the /wp-content/ directory. If you don’t see this file, you can always create one.

The WP_DEBUG_DISPLAY constant controls whether debug logs show up on the HTML page. Setting this to false will hide all errors, but you can review the errors later, as you’ve also defined WP_DEBUG_LOG as true.

Important: If you have WP_DEBUG enabled in the Kinsta environment, it’ll route all errors to the debug.log file and not the error.log in the MyKinsta dashboard.

You can also download the raw WordPress error log files via SFTP. Typically, you can find error logs in your server’s root directory in a folder named “logs.”

Accessing the WordPress error logs folder via SFTP

Accessing the WordPress error logs folder via SFTP

Kinsta users can also enable WordPress debug mode from their MyKinsta dashboard. To do that, navigate to Sites > Tools > WordPress Debugging and click the Enable button. This will allow you to see PHP errors and notices without enabling debug mode via SSH or SFTP.

Lastly, you can check the server log files. Depending on which server you’re using to host your WordPress site, they’re commonly found in these locations:

  • Apache: /var/log/apache2/error.log/
  • Nginx: /var/log/nginx/error.log/

You can refer to logging related documentation of Apache or Nginx for more information.

11. Configure Apache or Nginx Settings Properly

You can edit your server config files to increase resource limits for specific directives. This can help you resolve the 504 Gateway Timeout error.

For Apache Webservers

First, add the following code to your httpd.conf:

TimeOut 600

This setting defines how long the server will wait for certain requests before marking it as a network timeout issue. Its default value is 60 seconds (Apache 2.4 version).

You can only add this directive in your httpd.conf file, not in your .htaccess file. Since most shared hosting providers don’t allow you to modify the httpd.conf file, you can try increasing the value of the LimitRequestBody directive in your .htaccess file instead.

Then add the following line to your php.ini file:

max_execution_time 300

The default value of PHP’s max_execution_time directive is 30 seconds. Increasing it will allow your site’s PHP scripts to run longer.

For Nginx Webservers

If you’re running your WordPress sites on Nginx + FastCGI Process Manager (PHP-FPM) or using Nginx as a reverse proxy for Apache, you can tweak the server settings to help prevent 504 Gateway Timeout errors.

504 Gateway Timeout Error on Nginx + FastCGI (PHP-FPM)

First, you must edit your PHP-FPM pool config file. You can find it at the /etc/php7.4/fpm/pool.d/www.conf location in your Nginx server (the exact path may vary based on the PHP version). Alternately, you can run the following command in your terminal to edit the PHP-FPM pool config file:

sudo nano /etc/php/7.2/fpm/pool.d/www.conf

Next, set the following directive:

request_terminate_timeout = 300

After this, you must edit your php.ini file. You can locate it at /etc/php.ini. Open the file and add/change the value for the max_execution_time directive to 300 seconds.

max_execution_time = 300

Finally, add the following code to your nginx.conf file’s location block:

location ~ .php$ {
...
fastcgi_read_timeout 300;
}

Reload Nginx and PHP-FPM for the changes to take effect.

sudo service nginx reload
sudo service php7.4-fpm reload

The exact code to reload PHP-FPM will vary based on the PHP version installed on your server. Test your site to see whether it has fixed the issue.

504 Gateway Timeout Error on Nginx Proxy

If you’re using Nginx as a reverse proxy server for Apache, then you can make it more lenient towards server timeouts by adding the following directives to your nginx.conf file:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Don’t forget to reload Nginx after making your changes.

sudo service nginx reload

Other HTTP Errors Like 504 Gateway Timeout

As mentioned earlier in the article, many other HTTP 5xx errors are just like the 504 Gateway Timeout error. It’s because they all happen on the server-side. These errors include:

  • 500 Internal Server Error
  • 501 Not Implemented Error
  • 502 Bad Gateway Error
  • 503 Service Unavailable Error

Other HTTP errors caused due to client-side issues, like the 404 Not Found error, are also like the 504 error. You can refer to Kinsta’s detailed guide and list of HTTP status codes for more information.

When you don’t know what caused a 504 Gateway Timeout error, how do you fix it in time to keep hard-earned visitors from bouncing to competitor sites? 🤷‍♂️ All the details are in this post. ⬆️Click to Tweet

Summary

Your site can be affected by the 504 Gateway Timeout error because of multiple reasons. In this article, you learned how to troubleshoot them all. Typically, these errors are caused due to server-side issues, in which case you can reach out to your host and get it resolved quickly.

However, you must also understand that this error can be due to third-party plugins, themes, services, inefficient database queries, or a combination of two or more of these. If you’re maxing out your server’s resources (e.g. PHP workers), it’s recommended to optimize your site for performance.

If you still find that your website is timing out, then it might very well be that you need to upgrade your hosting plan or the number of PHP workers. I recommend you to consider this option only after you’ve exhausted all the other solutions described in this article.

From simple static sites to complex ecommerce and membership sites, Kinsta’s scalable hosting plans are designed to accommodate all types of websites. To learn more about our scalable cloud hosting, check out this article!

Did we miss anything? If you’re still finding it difficult to fix the 504 Gateway Timeout error on your site, leave a comment below.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. For many WordPress blogs and ecommerce platforms, knowing how to fix server errors like this is crucial to keep their hard-earned visitors from bouncing to competitor sites.

As the 504 Gateway Timeout error doesn’t tell you why it occurred, it’s hard to pinpoint what’s causing the server timeout. This article will help you understand it in detail, learn how to diagnose its cause, and then fix it.

After trying all the various solutions mentioned in the post, your site should be up and running in no time.

Sounds interesting? Let’s dive in!

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. 🤔 Learn how to fix it with this guide quickly. ⬇️Click to Tweet

Prefer to watch the video version?

What Is the 504 Gateway Timeout Error?

Every time you visit a website in your browser, the browser sends a request to the web server where the site is hosted. The server processes the request and responds with the requested resources.

Illustration of how HTTP requests and responses work

How HTTP requests and responses work.

The server response includes one of many HTTP status codes to indicate the response’s status to the browser. But not all these HTTP status codes are errors. For instance, a 200 OK status code means that the server processed the request successfully and “Everything is OK.”

The 5xx class of HTTP status codes indicates that something’s wrong with the server, the server is aware of it, and it cannot carry out the client request. As a result, they’re also referred to as Server Error 5xx status codes.

Officially, five status codes are specified under the 5xx class (500, 501, 502, 503, 504). You may come upon many unofficial codes too (506, 507, 509, 520, etc.).

The Internet Engineering Task Force (IETF) defines the 504 Gateway Timeout error as:

The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.

To simplify it further, this error occurs when two servers are involved in processing a request. The first server (typically the main server) times out, waiting for a response from the second server (upstream server).

The 504 Gateway Timeout error manifests itself in various forms. Here are some ways it usually shows up:

The HTTP ERROR 504 in Chrome browser

The ‘HTTP ERROR 504’ in the Chrome browser.

The 504 Gateway Timeout error is similar to the 502 Bad Gateway error, which indicates that the first server received an invalid response from the second server (upstream server).

504 GATEWAY TIMEOUT status code in Chrome DevTools

The ‘504 GATEWAY TIMEOUT’ status code in Chrome DevTools.

Variations of the 504 Gateway Timeout Error

The browser displays any 504 Gateway Timeout error inside it, just like any other error. As there are various operating systems, web servers, browsers, and user agents, it can show up in multiple ways.

Below are a few common 504 error message variations that you may run into:

  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • Gateway Timeout Error
  • Error 504
  • HTTP Error 504
  • HTTP Error 504 — Gateway Timeout
  • HTTP 504
  • 504 Error
  • Gateway Timeout (504)
  • This page isn’t working — Domain took too long to respond
  • 504 Gateway Time-out — The server didn’t respond in time
  • The page request was canceled because it took too long to complete
  • Site visitors: There was an issue serving your request, please try again in a few minutes.
  • Site Owners: There was a gateway timeout. You should visit your error log for more information.
  • A blank white screen

All the above error responses, though worded differently, point to the same 504 Gateway Timeout server error.

Web servers and websites can customize how they show the 504 Gateway Timeout error to users. Some of them can be cool! It’s an excellent tactic to quell their visitors’ disappointment.

GitHub’s customized HTTP 504 error page

GitHub’s customized HTTP 504 error page.

SEO Impact of the 504 Gateway Timeout Error

All 5xx errors prevent a webpage from loading, making them detrimental to user experience. Hence, search engines like Google take these errors seriously. If the error persists for a long duration, it may even lead to deindexing the webpage from the search engine results.

For example, when Google spiders stumble upon a 503 Service Unavailable error, they’ll understand that it’s a temporary issue as it’s mostly used to enable site maintenance mode. Thus, they’ll try to crawl the page again later.

A 504 Gateway Timeout error isn’t necessarily temporary as it can be due to multiple reasons. If your site is down for just a few minutes, and if the spiders are trying to crawl it multiple times every minute, they’ll try to serve the page from their cache.  They wouldn’t even notice it.

But if your site is down for 6+ hours or more, then Google will consider the 504 error as a serious site-wide issue that you need to fix as soon as possible. This can impact your SEO negatively.

Viewing the crawl errors in Google Search Console

Viewing the crawl errors in Google Search Console

Google Search Console is one of the best SEO tools to monitor your website’s HTTP 5xx errors.

Causes of the 504 Gateway Timeout Error

As the 504 error is due to a timeout between servers, the problem probably isn’t with the client’s device or internet connection. That also includes your device and connection.

A 504 Gateway Timeout error indicates that the web server is waiting too long to respond from another server and “timing out.” There can be many reasons for this timeout: the other server is not functioning properly, overloaded, or down.

The other server need not always be external (e.g. CDN, API gateway). It can also be a server-like entity within the main web server (e.g. reverse proxy server, database server).

How to Fix the 504 Gateway Timeout Error

Without knowing exact details about the site, such as its server configuration, hosting plan, third-party plugins, and the traffic it attracts, you may find it frustrating and overwhelming to fix a 504 Gateway Timeout error.

Since many variables are involved, I recommend you to start by fixing client-side issues, which are pretty rare, and then move towards fixing server-side problems. They’re usually the culprits with 504 errors.

  1. Try Reloading the Webpage
  2. Reboot Your Network Devices
  3. Check Your Proxy Settings
  4. Check for DNS Issues
  5. Disable Your Site’s CDN Temporarily
  6. Check Server Issues With Your Host
  7. Check for Spam, Bots, or DDoS Attacks
  8. Repair Your Corrupted WordPress Database
  9. Check Your Site’s Plugins and Themes
  10. Check Error Logs
  11. Configure Apache or Nginx Settings Properly

1. Try Reloading the Webpage

One of the first things you can try when encountering a 504 Gateway Timeout error is to wait a few minutes and try reloading the page.

You can press the F5 keyboard shortcut to refresh/reload the webpage in most browsers. To remove the page’s browser cache before reloading, you can press the CTRL+F5 shortcut combo instead.

Refreshing a webpage in Chrome browser

Refreshing a webpage in Chrome browser

While you’re at it, you can also try loading the site in a different browser to rule that out as an issue. As most 504 errors are due to temporarily overloaded servers, using this solution should make your site come right back.

If waiting and reloading the site doesn’t fix the 504 error issue, you can check whether a site is down for everyone or just you. Two useful online tools to test a site for downtime are Down for Everyone or Just Me and Is It Down Right Now?

Testing Kinsta.com on Down for Everyone or Just Me

Testing Kinsta.com on Down for Everyone or Just Me

2. Reboot Your Network Devices

Sometimes, problems with your network devices like modem or router could lead to a 504 Gateway Timeout error. Rebooting these devices could help you with fixing the problem.

While you can switch off all these networking devices in any order, the order you switch them back on is important. Typically, turn these devices on from the “outside-in,” following the connection order from the internet service provider to your main client device.

3. Check Your Proxy Settings

A proxy server sits between your device and the internet. It’s mostly used to enhance online privacy by hiding private information (e.g. device location) from websites and webservers (e.g. using a VPN).

While it’s rare for proxy servers to cause a 504 error, incorrect proxy server settings can sometimes be the reason. You can disable the proxy server and try reloading the webpage to see whether it’ll fix the error.

Changing the ‘Proxy’ settings in Windows 10

Changing the ‘Proxy’ settings in Windows 10

Most clients don’t use a proxy service, so you can skip this step if you’re confident that you don’t use any proxy server. However, you might have set it without you even knowing about it. I’d suggest you check your device’s and browser’s proxy settings to rule this cause out.

4. Check for DNS Issues

A 504 Gateway Timeout error can also be caused by DNS issues on the server-side or the client-side (or both).

The most probable reason for a server-side DNS issue is the FQDN (fully qualified domain name) not resolving the correct IP address or the DNS server not responding. Usually, this occurs when you’ve just migrated your site to a new server or host. Hence, it’s important to wait for the domain’s DNS records to propagate fully, which can take up to 24 hours.

You can use free tools like whatsmydns.net DNS Checker or DNSMap to see if your DNS has propagated around the globe.

Checking DNS propagation for your domain on whatsmydns.net

Checking DNS propagation for your domain on whatsmydns.net

For fixing client-side DNS issues, you could try flushing your local DNS cache. It’s like clearing your browser cache, except here, you’re flushing the DNS cache from the operating system.

If you’re using Windows, you can flush the DNS cache by opening the Command Prompt and entering the following directive:

ipconfig /flushdns

Flushing the DNS Cache with Command Prompt

Flushing the DNS Cache with Command Prompt in Windows

You should see a “Successfully flushed the DNS resolver Cache.” message if it worked.

For the latest macOS versions, you can open the Terminal and run the following command:

sudo killall -HUP mDNSResponder

You won’t see any notification in macOS when the process finishes, but you can change that by appending the command with your custom message.

sudo killall -HUP mDNSResponder; DNS Cache was cleared successfully

If you’re using older macOS versions, the command you need to enter varies based on which version of macOS you’re running. For more details, you can refer to the macOS section in Kinsta’s in-depth flush DNS tutorial.

If you’re using the Linux operating system, then the process is quite similar to macOS as even Linux uses the Terminal as its command-line interface. Since there are many Linux distributions, the exact command you need to run may vary from one distro to another. You can check out Kinsta’s guide for more information.

Finally, you can change your client-side DNS servers temporarily. By default, your ISP assigns the DNS servers automatically to you. But you can change these to public DNS IPs temporarily.

Some reliable DNS servers you can try out are Google Public DNS, Cloudflare 1.1.1.1, Quad9 DNS, and Cisco OpenDNS.

Settings custom DNS servers in Windows 10

Settings custom DNS servers in Windows 10

5. Disable Your Site’s CDN Temporarily

Sometimes, the issue could also be with your content delivery network (CDN). If a site’s origin server isn’t reachable, most CDNs will try to serve the full webpage from their cache.

But most CDNs don’t enable this feature by default as it’s complex to cache dynamic assets on most sites (e.g. the WordPress admin dashboard).

Setting the ‘Cache Everything’ page rule in Cloudflare

Setting the ‘Cache Everything’ page rule in Cloudflare

A straightforward way to troubleshoot this is to disable your CDN temporarily. For example, if you’re using the free CDN Enabler WordPress plugin to link your site assets to the CDN URLs, then you can deactivate the plugin and test reloading your site.

The same goes for using any other plugin you may use to connect to your CDN (e.g. WP Rocket, Breeze, W3 Total Cache).

If you can’t access your site’s admin dashboard, you can disable the plugin via SFTP by renaming the plugin’s folder name.

Disable all plugins via SFTP by renaming the plugins folder name

Disable all plugins via SFTP by renaming the plugins folder name

CDNs like Cloudflare or Sucuri, which provide full proxy services, have extra firewalls between their edge servers and your origin server. Hence, you may encounter HTTP 5xx errors more frequently while using them. Most of them cache 5xx errors returned by your origin server, so it’s easy to troubleshoot them.

Cloudflare’s free plan is prone to throw up a 5xx error. Unfortunately, since it’s a full proxy service, there’s no quick way to disable it. But before you blame Cloudflare for it, know that Cloudflare shows two variations of the 504 Gateway Timeout error.

504 Gateway Timeout at Cloudflare (Variation 1)

Cloudflare will show you a custom 504 Gateway Timeout error screen when your site’s origin server responds with a standard HTTP 504 response.

Cloudflare’s custom Error 504 screen

Cloudflare’s custom Error 504 screen

Here, the issue lies with your web server and not Cloudflare. You can try fixing it with the other solutions mentioned below or contact your hosting provider’s support for technical help.

504 Gateway Timeout at Cloudflare (Variation 2)

If Cloudflare causes the 504 Gateway Timeout error, the error screen will mention “cloudflare,” which is currently the standard server name for all Cloudflare assets. Usually, the error screen will appear as below:

504 Gateway Timeout error caused by Cloudflare

Error screen for 504 Gateway Timeout caused by Cloudflare

Since Cloudflare itself is unresponsive, you’ll not see any Cloudflare-branded error screen here.

Most likely, Cloudflare is already aware of the issue and is working on a fix already. You can confirm this by checking the Cloudflare System Status webpage. Alternatively, you can get in touch with Cloudflare support for a quicker resolution.

Check Cloudflare System Status at cloudflarestatus.com

Check Cloudflare System Status at cloudflarestatus.com

504 Gateway Timeout at Cloudflare Due to Large Uploads

The size of your uploads to your site can also be a reason for the server timeouts. Cloudflare limits upload file size (per HTTP POST request) to just 100 MB on both Free and Pro plans.

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

The issue can be on your host’s end or with Cloudflare. You can find out the exact cause by bypassing Cloudflare with your DNS hosts file and trying your upload again.

If you’re using Cloudflare with WordPress, I recommend using their free plugin and excluding critical URLs from caching (such as the WordPress admin dashboard). You can refer to Kinsta’s detailed post on how to configure Cloudflare settings for WordPress.

Suggested reading: How to Set up Cloudflare APO for WordPress.

6. Check Server Issues With Your Host

Server issues are one of the most common reasons for facing a 504 Gateway Timeout error. Since most WordPress sites are hosted on Nginx or Apache webservers, Nginx or Apache is waiting for a response from something and timing out.

Many clients come to Kinsta for exactly this problem they’re facing at other hosts. The conversation goes something like this:

We’re getting around 100k visitors per month with more than 200k views. Currently, we’re hosting with ____ and we experience 504 errors constantly due to server overload. I don’t like how ____ handled the problem, and we were also advised that we will have to move to their dedicated plans soon, which I believe is not necessary.

High-traffic and ecommerce sites are more prone to getting 504 errors because of server overload as they generate many uncacheable requests. However, this issue can crop with any site, including simple blogs. Many hosts will ask you to upgrade to a high-tier plan to fix the issue, which in most cases is unnecessary.

Kinsta uses LXD managed hosts and orchestrated LXC software containers for each site. Thus, every site is housed in its own isolated container with access to all the software required to run it (Linux, Nginx, PHP, MySQL). The resources are 100% private and aren’t shared with any other site, even your sites.

Most hosts providing shared hosting plans don’t have this capability. Hence, a high-traffic site hosted on the same server as yours may cause your site to throw up a 504 error too.

Apart from isolating each site in its container, Kinsta has also designed its infrastructure to handle thousands of concurrent connections easily. Kinsta even hosts the MySQL databases at localhost, not a remote server. This means no latency between machines, resulting in faster queries and fewer chances of timeouts occurring.

Many clients who migrate to Kinsta see huge decreases in overall load times.

A 212.5% increase in performance after switching to C2.

A 212.5% increase in performance after switching to C2.

An overloaded server isn’t the only cause for a server timeout. There can be many other reasons for the 504 error:

Slow Server Infrastructure

The server you use to host your site may not have enough resources to handle the load. It’s like playing a modern, graphics-intensive videogame on a decade-old PC.

The server just hangs up trying to serve the website. The only solution to this problem is to upgrade to a server with better infrastructure. For this reason, even Kinsta’s most basic hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic. If all the server’s PHP workers are busy, they’ll build up a queue.

When the queue gets too big, the server disregards old requests, which may cause the server to throw up a 504 gateway error. You can ask your host about increasing your number of PHP workers. This’ll allow your site to execute multiple requests simultaneously.

Firewall Issues

Your server’s firewall could have some errors or an improper configuration. Perhaps, a few of its rules prevent the server from establishing a connection properly. To know if your firewall is the culprit, you can check your server’s error logs.

Network Connectivity Problems

Connectivity issues between the proxy server and the web server could cause delays in responding to HTTP requests. If you use a load balancer, there could also be network connectivity issues with it.

HTTP Timeouts

HTTP timeouts can occur when a connection between the web server and the client is kept open for too long. With WordPress sites, this usually happens when running WordPress imports. One way to resolve this issue is to switch to a faster internet connection.

You can also use a tool with support for WP-CLI to run the scripts directly on the server, bypassing the HTTP connection entirely. For instance, you can use the wp import WP-CLI command to run the WordPress Importer plugin directly through the command-line interface.

Important: 504 Gateway Timeout errors look similar to 503 Service Unavailable errors or 502 Bad Gateway errors. But they’re all different. If you’re experiencing a 504 error at Kinsta, open a support ticket to get your issue fixed immediately.

For monitoring your site’s downtime on your own, you can use a tool like updown.io. It’ll check your website’s status (or any URL) periodically by sending an HTTP request to it. You can set the check frequency from 15 seconds to 1 hour. If your website isn’t responding correctly, it’ll notify you with an email or an SMS.

Monitor your website with updown.io

Monitor your website easily with updown.io

You’ll get a generous quantity of free credits with every account of updown.io, but if you’re looking for cheaper alternatives, you can check out WebGazer or UptimeRobot. Both these tools will help you monitor your site’s uptime every 5 minutes for free. That’s decent enough for most website owners.

WebGazer website monitoring tool's dashboard

WebGazer website monitoring tool’s dashboard

Monitoring your website will give you an idea of how often it’s down. This is especially helpful if you’re using a shared hosting provider. Most application, database, and managed WordPress hosts (like Kinsta) take care of this automatically for you. Hence it’s always recommended to go with them.

For a detailed explanation, check out Kinsta’s post on the importance of managed WordPress hosting.

7. Check for Spam, Bots, or DDoS Attacks

Malicious attackers can bring your web server to a crawl by sending too many and/or resource-intensive requests. If your site is getting spammed by bots or undergoing a DDoS attack, it can overwhelm your server and result in 504 Gateway Timeout errors for many genuine users.

You can look at your server traffic and analytics to see if you can spot any irregular patterns in the site traffic. If you’re using Kinsta to host your site, you can view this data easily by going to your MyKinsta Analytics dashboard.

MyKinsta Analytics dashboard

MyKinsta Analytics dashboard

Start your investigation by looking at the top client IPs. It’ll give you an idea of who generates the maximum number of requests, and from where. If your server suddenly uses up enormous bandwidth or attracts a lot of traffic, then this report will come in super handy.

Viewing ‘Top Client IPs’ in MyKinsta dashboard

Viewing ‘Top Client IPs’ in MyKinsta dashboard

Next, you can check out the Cache Analysis report. Here, you can see how many requests are bypassing or missing the cache, or being served from the cache. For performance and stability reasons, you want to cache as many requests as possible, but it’s not always possible to achieve that.

For example, WooCommerce sites generate many uncacheable requests for features such as the shopping cart and the checkout process.

The ‘Cache Analysis’ screen in MyKinsta

The ‘Cache Analysis’ screen in MyKinsta

Finally, you can use a security plugin to beef up your website’s security by spotting and blocking worrisome traffic/IPs. You can ask your host to block certain IPs too.

Depending upon the length and scale of the attack, this could be a never-ending process of blacklisting IPs as many attackers change their IPs and proxy addresses after getting blocked.

Note: Kinsta doesn’t allow its clients to install security plugins as they can have a huge effect on the site’s performance, especially its scanning capabilities. As Kinsta uses load balancers with Google Cloud Platform, blocking IPs wouldn’t always work as intended.

You can use dedicated security solutions such as Cloudflare or Sucuri to protect your sites from DDoS attacks and spambots. For more, you can check out Kinsta’s articles on how to install Cloudflare on your site and how Sucuri helped stop a DDoS attack in its tracks.

8. Repair Your Corrupted WordPress Database

Sometimes, a 504 Gateway Timeout error can be because of a corrupt database, especially in WordPress sites. Typically, this is due to corrupted database tables or files. Sometimes, it can also be caused by a serious security issue like your site or database being hacked.

Repairing a corrupted WordPress database depends on the problem. Plugins like WP-DBManager make it easy to diagnose database issues and repair them. I recommend you to read Kinsta’s detailed walkthrough on repairing WordPress database issues to get started.

9. Check Your Site’s Plugins and Themes

In most cases, third-party plugins and themes don’t cause 504 errors. But there’s a slight chance that they might cause server timeouts, usually by queuing up many uncached requests generated by the plugin/theme. As this ties up a lot of your server’s PHP workers, it can cause 504 errors.

A great example of this issue is WooCommerce, a plugin installed to add ecommerce functionality to WordPress sites.

The simplest way you can troubleshoot this problem is by deactivating all your plugins. Remember, you won’t lose any data if you just deactivate a plugin.

If you can access your admin dashboard, you can go to the Plugins screen, select Deactivate from the bulk actions menu, checkmark all the plugins, and then hit the Apply button. This will disable all of your plugins.

Deactivate plugins in WordPress

Deactivating all the WordPress plugins through WP admin dashboard

If you can’t access your admin area, you can disable plugins via SFTP using the method described before. Just rename the main plugin folder name to disable all the plugins in bulk.

Once you’ve deactivated all the plugins, check whether your site loads properly. If it works, you must activate each plugin, testing the site after enabling every plugin.

Finally, make sure that your plugins, themes, and WordPress core are up to date. Also, ensure that your server is running the recommended version of PHP.

If you feel this to be too overwhelming, you can always reach out to your host for help. Kinsta uses Kinsta APM and other troubleshooting techniques to help clients narrow down what plugin, query, or script might cause the error.

In the worst-case scenarios, like an inefficient query or bad code in a plugin/theme, you can bring in a WordPress developer to fix the issue.

10. Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your site. This can help you narrow down an issue on your site quickly, especially if it’s resulting from a demanding plugin on your site.

If you’re a Kinsta customer, you can easily see errors in the log viewer in your MyKinsta dashboard.

Checking error logs inside MyKinsta dashboard

Checking error logs inside the MyKinsta dashboard

If your host doesn’t have a logging tool, then you can enable WordPress debug mode by adding the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

The WP_DEBUG constant enables or disables the WordPress debug mode. It has two optional companion constants that can extend its features. The WP_DEBUG_LOG constant directs all errors to be saved to a debug.log file within the /wp-content/ directory. If you don’t see this file, you can always create one.

The WP_DEBUG_DISPLAY constant controls whether debug logs show up on the HTML page. Setting this to false will hide all errors, but you can review the errors later, as you’ve also defined WP_DEBUG_LOG as true.

Important: If you have WP_DEBUG enabled in the Kinsta environment, it’ll route all errors to the debug.log file and not the error.log in the MyKinsta dashboard.

You can also download the raw WordPress error log files via SFTP. Typically, you can find error logs in your server’s root directory in a folder named “logs.”

Accessing the WordPress error logs folder via SFTP

Accessing the WordPress error logs folder via SFTP

Kinsta users can also enable WordPress debug mode from their MyKinsta dashboard. To do that, navigate to Sites > Tools > WordPress Debugging and click the Enable button. This will allow you to see PHP errors and notices without enabling debug mode via SSH or SFTP.

Lastly, you can check the server log files. Depending on which server you’re using to host your WordPress site, they’re commonly found in these locations:

  • Apache: /var/log/apache2/error.log/
  • Nginx: /var/log/nginx/error.log/

You can refer to logging related documentation of Apache or Nginx for more information.

11. Configure Apache or Nginx Settings Properly

You can edit your server config files to increase resource limits for specific directives. This can help you resolve the 504 Gateway Timeout error.

For Apache Webservers

First, add the following code to your httpd.conf:

TimeOut 600

This setting defines how long the server will wait for certain requests before marking it as a network timeout issue. Its default value is 60 seconds (Apache 2.4 version).

You can only add this directive in your httpd.conf file, not in your .htaccess file. Since most shared hosting providers don’t allow you to modify the httpd.conf file, you can try increasing the value of the LimitRequestBody directive in your .htaccess file instead.

Then add the following line to your php.ini file:

max_execution_time 300

The default value of PHP’s max_execution_time directive is 30 seconds. Increasing it will allow your site’s PHP scripts to run longer.

For Nginx Webservers

If you’re running your WordPress sites on Nginx + FastCGI Process Manager (PHP-FPM) or using Nginx as a reverse proxy for Apache, you can tweak the server settings to help prevent 504 Gateway Timeout errors.

504 Gateway Timeout Error on Nginx + FastCGI (PHP-FPM)

First, you must edit your PHP-FPM pool config file. You can find it at the /etc/php7.4/fpm/pool.d/www.conf location in your Nginx server (the exact path may vary based on the PHP version). Alternately, you can run the following command in your terminal to edit the PHP-FPM pool config file:

sudo nano /etc/php/7.2/fpm/pool.d/www.conf

Next, set the following directive:

request_terminate_timeout = 300

After this, you must edit your php.ini file. You can locate it at /etc/php.ini. Open the file and add/change the value for the max_execution_time directive to 300 seconds.

max_execution_time = 300

Finally, add the following code to your nginx.conf file’s location block:

location ~ .php$ {
...
fastcgi_read_timeout 300;
}

Reload Nginx and PHP-FPM for the changes to take effect.

sudo service nginx reload
sudo service php7.4-fpm reload

The exact code to reload PHP-FPM will vary based on the PHP version installed on your server. Test your site to see whether it has fixed the issue.

504 Gateway Timeout Error on Nginx Proxy

If you’re using Nginx as a reverse proxy server for Apache, then you can make it more lenient towards server timeouts by adding the following directives to your nginx.conf file:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Don’t forget to reload Nginx after making your changes.

sudo service nginx reload

Other HTTP Errors Like 504 Gateway Timeout

As mentioned earlier in the article, many other HTTP 5xx errors are just like the 504 Gateway Timeout error. It’s because they all happen on the server-side. These errors include:

  • 500 Internal Server Error
  • 501 Not Implemented Error
  • 502 Bad Gateway Error
  • 503 Service Unavailable Error

Other HTTP errors caused due to client-side issues, like the 404 Not Found error, are also like the 504 error. You can refer to Kinsta’s detailed guide and list of HTTP status codes for more information.

When you don’t know what caused a 504 Gateway Timeout error, how do you fix it in time to keep hard-earned visitors from bouncing to competitor sites? 🤷‍♂️ All the details are in this post. ⬆️Click to Tweet

Summary

Your site can be affected by the 504 Gateway Timeout error because of multiple reasons. In this article, you learned how to troubleshoot them all. Typically, these errors are caused due to server-side issues, in which case you can reach out to your host and get it resolved quickly.

However, you must also understand that this error can be due to third-party plugins, themes, services, inefficient database queries, or a combination of two or more of these. If you’re maxing out your server’s resources (e.g. PHP workers), it’s recommended to optimize your site for performance.

If you still find that your website is timing out, then it might very well be that you need to upgrade your hosting plan or the number of PHP workers. I recommend you to consider this option only after you’ve exhausted all the other solutions described in this article.

From simple static sites to complex ecommerce and membership sites, Kinsta’s scalable hosting plans are designed to accommodate all types of websites. To learn more about our scalable cloud hosting, check out this article!

Did we miss anything? If you’re still finding it difficult to fix the 504 Gateway Timeout error on your site, leave a comment below.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Нет ничего более раздражающего, чем появление белого экрана с ошибкой при обращении к WordPress сайту. Некоторые из распространенных ошибок, с которыми вы могли сталкиваться ранее: белый экран смерти, ошибка установки соединения с базой данных и т.д. Для большинства блогов, а также сайтов, связанных с электронной коммерцией, появление таких ошибок приводит к потере дохода, поскольку посетители сразу покидают такой ресурс, а клиенты не могут совершить покупки. Сегодня мы рассмотрим ошибку 504 Gateway Timeout Error, а также дадим рекомендации по поводу того, как справиться с ней на своем WordPress сайте. Читайте далее о причинах этой ошибки и о том, как предотвратить ее появление.

Содержание

  1. Почему появляется 504 Gateway Timeout Error?
  2. Варианты ошибки 504 Gateway Timeout Error
  3. Попробуйте перезагрузить страницу.
  4. Отключите параметры прокси.
  5. Проблемы с DNS.
  6. Временно отключите CDN
  7. Проблемы с сервером (проверьте ваш хост)
  8. Спам, боты и DDoS-атаки
  9. Проверьте ваши плагины и темы.
  10. Проверьте логи.
  11. Параметры Nginx
  12. Заключение

Почему появляется 504 Gateway Timeout Error?

Перед тем, как мы рассмотрим саму ошибку, важно понять, из-за чего она появляется. Всякий раз, когда вы запускаете свой браузер и посещаете сайт, он передает запрос обратно на сервер, на котором размещен. Затем веб-сервер обрабатывает запрос и отправляет вам запрашиваемые ресурсы вместе с HTTP-заголовком. Этот заголовок содержит один из многочисленных кодов состояния HTTP, который позволяет понять, все ли в порядке или что-то пошло не так. Далеко не все коды состояния плохие. К примеру, код состояния 200 говорит о том, что все в порядке.

Существует много различных кодов ошибок 500 (500, 501, 502, 503, 504 и т.д.), которые имеют разное значение. Они указывают, что запрос был принят, но сервер не смог выполнить его.

В данном случае ошибка 504 означает, что «для сервера, работающего в качестве шлюза, вышло время ожидания ответа от другого сервера». Код возвращается, когда есть два сервера, участвующих в обработке запроса, и время ожидания ответа от второго сервера со стороны первого сервера истекло (RFC 7231, раздел 6.6.5).

Варианты ошибки 504 Gateway Timeout Error

Вследствие многообразия веб-браузеров, операционных систем и серверов ошибка 504 может быть представлена разными способами. Все они, как правило, несут в себе одно и то значение. Ниже приведены некоторые из вариантов, с которыми вы можете столкнуться:

  • “504 Gateway Timeout”
  • “504 Gateway Timeout NGINX”
  • “NGINX 504 Gateway Timeout”
  • “Gateway Timeout Error”
  • “Error 504”
  • “HTTP Error 504”
  • “HTTP Error 504 – Gateway Timeout”
  • “HTTP 504”
  • “504 Error”
  • “Gateway Timeout (504)
  • “504 Gateway Time-out – The server didn’t respond in time”

Как справиться с ошибкой 504 Gateway Timeout Error

С чего следует начать решение проблем, если вы столкнулись с ошибкой 504 Gateway Timeout Error на своем WordPress сайте? Не имея контекста, достаточно сложно понять, что делать в первую очередь. Как правило, ошибку вызывают проблемы с сетевым подключением и проблемы с сервером, на котором расположен сайт. Однако ошибка может быть следствием проблем на стороне клиента или даже результатом использования стороннего плагина. Мы немного углубимся в этот вопрос. Давайте ознакомимся с популярными причинами появления ошибки, а также рассмотрим то, как исправить ее.

  1. Попробуйте перезагрузить страницу.

Одна из первых вещей, которую вы должны сделать, столкнувшись с ошибкой 504 Gateway Timeout Error – это просто подождать минуту и перезагрузить страницу. Возможно, хостинг или сервер просто перегружен, и сайт быстро вернется в работу. Вы можете также попробовать другой браузер.

Еще одна вещь, которую вы можете сделать – это проверить статус вашего сайта на downforeveryoneorjustme.com. Этот сайт подскажет вам, вышел ли сайт из строя только у вас или же у всех посетителей. Инструмент проверяет код состояния HTTP, который возвращается сервером. Если код отличается от 200, то в таком случае вы увидите указатель Down (т.е. сайт «лежит» для всех).

  1. Отключите параметры прокси.

Иногда вы можете столкнуться с ошибкой 504, если вы используете прокси-сервис. Эти случаи являются очень редкими, особенно на стороне клиента. Однако иногда такие настройки могут быть установлены без ведома клиента. В сети есть руководства, посвященные отключению настроек прокси на Windows и Mac.

  1. Проблемы с DNS.

Ошибка 504 gateway timeout может быть вызвана проблемами с DNS. Такая ошибка может возникать с двух сторон. На стороне сервера она происходит, к примеру, когда домен не преобразован в корректный IP. Если вы только что перенесли свой сайт WordPress на новый хостинг, то важно дождаться распространения DNS. Обычно это занимает до 24 часов. Все зависит от значения TTL ваших DNS-записей. Вы можете использовать бесплатный инструмент, такой как DNSMap, чтобы проверить, распространились ли ваши DNS по всему миру.

Вторая проблема с DNS связана уже с клиентской стороной. В этом случае вы можете очистить свой локальный DNS кэш. Это похоже на очистку кэша браузера.

В Windows просто откройте командную строку и введите следующее:

ipconfig /flushdns

Вы должны увидеть сообщение «Successfully flushed the DNS resolver Cache».

В macOS введите следующее в терминал:

dscacheutil -flushcache

Примечание: на Mac нет сообщений об успешном завершении.

И, наконец, вы можете временно изменить ваши клиентские DNS-серверы. По умолчанию DNS-серверы автоматически привязываются вашим интернет-провайдером. Вы можете временно сменить их на публичный DNS-сервер, такой как Google. Некоторые предпочитают постоянно использовать публичные DNS Google, поскольку они в некоторых случаях могут быть более надежными.

  1. Временно отключите CDN

Также проблема может связана с CDN (сетью доставки контента). Если вы используете стороннего CDN провайдера, вы можете просто временно отключить ваш CDN. К примеру, нам нравится бесплатный плагин CDN Enabler. Если вы используете его, вы можете просто отключить плагин, чтобы проверить работу сайта. Перестали попадать в консоль WordPress после этого? В таком случае войдите на сайт через SFTP и переименуйте папку с плагином в cdn-enabler_old. В итоге ваше CDN соединение будет временно отключено. То же самое касается плагина WP Rocket или любого другого плагина, который подцеплялся к CDN.

Иногда эта ошибка может быть следствием использования прокси-сервисов, таких как Cloudflare или Sucuri, поскольку у них есть дополнительные файрволы. Большинство из них кэшируют коды состояния 500, когда они возвращаются вашим исходным сервером. Мы заметили, что это время от времени происходит на бесплатном тарифе Cloudflare. К сожалению, поскольку Cloudflare является полным прокси-сервисом, быстрого способа его отключения не существует.

Однако, прежде чем грешить на Cloudflare, важно знать, что есть два типа ошибки 504:

504 Gateway Timeout в Cloudflare (вариант 1)

Если вы видите следующую страницу, то в данном случае проблема на стороне Cloudflare. Обратитесь к ним в поддержку. Либо проверьте их страницу со статусом. Скорее всего, они уже уведомлены о данной проблеме и работают над ней.

504 Gateway Timeout в Cloudflare (вариант 2)

Если вы видите следующую страницу, то это проблема с вашим хостом WordPress (исходный сервер), и в этом случае вам нужно воспользоваться рекомендацией под номером 5.

  1. Проблемы с сервером (проверьте ваш хост)

Проблемы с сервером – одна из распространенных причин, почему пользователи сталкиваются с ошибками 504 на своих WordPress-сайтах. Говоря простым языком, Nginx или Apache ожидают ответа от второй стороны, и время ожидания истекло.

Ошибки 504 чаще всего встречаются на сайтах с высоким трафиком и на сайтах электронной коммерции (с установленным WooCommerce, к примеру), у которых много некэшируемых запросов. Это может вызывать перегрузку сервера. Однако мы сталкивались с такими ошибками на разных типах сайтов, в том числе и на обычных блогах. Многие хостинги отвечают стандартными фразами по типу «вам нужно перейти на более дорогостоящий тарифный план, чтобы исправить эту проблему». И пусть это обычно помогает решить данную проблему, зачастую это не является необходимым.

Хостинги, такие как, к примеру, Kinsta, используют контейнеры LXD для каждого сайта. Это означает, что каждый сайт размещается в своем изолированном контейнере, в котором имеются все необходимые программные ресурсы, требуемые для его запуска (Linux, Nginx, PHP, MySQL). Ресурсы на 100% конфиденциальны и не делятся ни с кем. Многие виртуальные хостинги WordPress не имеют данной возможности, поэтому любой соседний сайт с высоким трафиком будет вызывать ошибки 504 на вашем сайте.

В Kinsta инфраструктура построена так, чтобы легко обрабатывать тысячи одновременных подключений. Даже базы данных MySQL размещаются на локальном хосте, а не на удаленном сервере. Это гарантирует отсутствие задержки между машинами, что приводит к более быстрым запросам и меньшей вероятности возникновения тайм-аута между ними.

Помимо тайм-аутов сервера из-за повышенной нагрузки есть и другие причины, в результате чего может возникнуть ошибка 504:

  • Медленный сервер. Вполне возможно, что сервер, на котором расположен ваш WordPress сайт, слишком медленно отвечает на запросы, и поэтому он генерирует ошибки шлюза.
  • Недостаточно PHP воркеров. PHP-воркеры используются для выполнения кода на вашем WordPress-сайте. На требовательных в плане ресурсов сайтах вполне может быть так, что все PHP-воркеры заняты, и в этом случае они начинают формировать очередь. Если очередь и бэклог заполнены, старые запросы начинают игнорироваться. Вы можете попросить ваш хостинг увеличить количество PHP-воркеров. Дополнительные PHP-воркеры для сайта позволяют одновременно выполнять несколько запросов.
  • Проблемы с файрволом. Файрвол на вашем сервере может содержать ошибки в результате неверной конфигурации или правил, препятствующих установлению соединения.
  • Сетевое подключение. Если возникают проблемы с сетевым подключением между прокси-сервером и веб-сервером, то это может вести к задержкам с ответом для HTTP-запросов. Также могут возникать сетевые проблемы с балансировщиком нагрузки, если он используется.

Также важно отметить, что ошибки 504 могут обманчиво выглядеть как ошибки 503 (сервис недоступен) или даже ошибки 502 (bad gateway), но на практике они отличаются.

Если вы хотите предотвратить появление таких ошибок в будущем, вы можете воспользоваться инструментом, таким как updown.io, для отслеживания ситуации и немедленного уведомления о любых проблемах. Сервис периодически отправляет HTTP HEAD-запрос к указанному URL. Вы можете просто задать вашу главную страницу. Можно задавать частоту проверок:

  • 15 сек
  • 30 сек
  • 1 мин
  • 2 мин
  • 5 мин
  • 10 мин

Он пришлет вам электронное письмо, если ваш сайт перестал работать, с указанием времени, когда это случилось. Ниже приведен пример:

Это может быть особенно полезно, если вы используете виртуальный хостинг, который, как правило, работает на пределе возможностей. Это даст вам доказательство того, что ваш сайт не работал (к примеру, ночью). По этой причине мы и советуем переходить к администрируемым (управляемым) хостингам.

  1. Спам, боты и DDoS-атаки

Может быть так, что ваш сайт был заспамлен ботами или подвержен DDoS-атаке. Иногда это ведет к некэшируемым запросам и, как следствие, к перегрузке сервера, что и выливается в ошибку 504 gateway timeout. Вы можете изучить аналитику сервера, чтобы увидеть, есть ли в ней какие-либо паттерны. В Kinsta имеется, к примеру, инструмент MyKinsta для аналитики. Вы можете попросить эти данные у вашего хостинга.

Первый отчет, который мы советуем изучить – это IP-адреса топовых клиентов. Обычно это очень полезно, особенно если ваш сайт внезапно стал генерировать большой трафик или попал под атаку ботов.

Второй отчет, который мы рекомендуем посмотреть – это запросы и боты. Вы можете быстро сравнить количество людей, попадающих на ваш сайт, с количеством ботов и роботов. Однако помните, что не все боты плохие. GoogleBot – пример хорошего бота, он сканирует сайт для индексации содержимого в результатах поиска.

Третий отчет, который мы рекомендуем посмотреть – это анализ кэша. Здесь вы можете видеть, какие запросы отсутствуют в кэше, а также каковы топовые локации вашего сайта. По причинам производительности и стабильности вы должны стараться закэшировать как можно больше запросов. Это не всегда возможно, поскольку некоторые сайты генерируют большое количество некэшируемых запросов (как в случае с WooCommerce), и они нужны для того, чтобы функционал (к примеру, корзина товаров или процесс покупки) работал правильно и синхронизировался.

Если вы обнаружите и идентифицируете трафик/IP-адреса, которые должны быть заблокированы на вашем сайте, вы можете затем воспользоваться плагином безопасности WordPress. Однако не все хостинги позволяют устанавливать плагины безопасности. Kinsta, к примеру, запрещает, что сделано по нескольким причинам. Во-первых, такие плагины отражаются на производительности, особенно возможности сканирования. Во-вторых, функции блокировки IP в них не работают, поскольку хостинг использует балансировщики нагрузки с Google Cloud Platform.

Естественно, IP-адреса могут быть всегда заблокированы службой поддержки хостинга, однако, в зависимости от длительности и масштабов атаки, это может превратиться в бесконечный процесс. Многие атаки или спам при блокировке в одной области переключаются на другие зоны, меняют IP-адреса или прокси. Поэтому в данном случае мы рекомендуем установить решение безопасности, такое как Cloudflare или Sucuri.

  1. Проверьте ваши плагины и темы.

Многие считают, что сторонние плагины или темы не приводят к ошибкам 504 gateway timeout. И в большинстве случаев это верно. Но, по нашему опыту, медленный некэшируемый запрос от плагина может привести к задержкам, поскольку он задействует больше ваших PHP-воркеров. Как только вы достигнете предела PHP-воркеров, очередь будет убирать ваши прошлые запросы, что может вести к ошибкам 504. Их не следует путать с ошибками 502, когда ошибка появляется в результате достижения таймаута в 60 секунд в очереди.

Есть несколько способов устранения этой проблемы. Один из них — деактивация всех ваших плагинов. Помните, что вы не потеряете никаких своих данных, если отключите плагин. Если у вас есть доступ к панели администратора, просто перейдите к разделу с плагинами и выберите «Деактивировать» из меню с массовыми действиями. Это приведет к отключению всех ваших плагинов.

Если это устранило проблему, вам нужно найти ее виновника. Начинайте активировать плагин один за другим, перезагружая сайт после каждой активации. Как только вы увидите ошибку 504, вы сможете идентифицировать проблемный плагин. Затем вы можете обратиться к разработчику плагина за помощью или опубликовать тикет в репозитории WordPress.

Если у вас нет доступа к панели администратора, вы можете использовать FTP-клиент для подключения к своему серверу и переименования папки с плагинами в нечто вроде plugins_old. Затем проверьте свой сайт еще раз. Если это сработает, вам нужно будет протестировать каждый плагин по отдельности, чтобы найти виновника. Переименуйте папку с плагинами обратно в plugins и затем начинайте переименовывать папки отдельных плагинов внутри нее, пока не обнаружите проблемный плагин. То же самое можно сделать и на тестовом сайте.

Обязательно убедитесь в том, что все ваши плагины, темы и ядро WordPress обновлены до последней версии. И убедитесь, что вы используете поддерживаемую версию PHP.

Если плагин будет содержать плохой код, то вам, скорее всего, понадобится обратиться к разработчикам WordPress, чтобы решить эту проблему.

  1. Проверьте логи.

Вы также можете использовать ваши журналы (логи) ошибок. В Kinsta ошибки можно просмотреть в специальном разделе консоли MyKinsta. Вы сможете быстро установить проблему, особенно если ее источником является плагин на сайте. Если ваш хостинг не предлагает инструментов для ведения логов, вы можете добавить следующий код в файл wp-config.php, чтобы включить логгинг:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

Логи обычно расположены в каталоге /wp-content. Иногда они могут находиться в отдельных папках.

Вы можете также проверить логи в Apache и Nginx, которые чаще всего находятся по адресу:

Apache: /var/log/apache2/error.log

Nginx: /var/log/nginx/error.log

  1. Параметры Nginx

Если вы обслуживаете свой собственный сервер и WordPress сайты на Nginx + FastCGI (php-fpm) или Nginx как прокси для Apache, то в таком случае есть дополнительные настройки, которые вы можете изменить, чтобы предотвратить появление ошибок 504 gateway timeout.

Если вы используете Nginx с FastCGI (php-fpm), то в таком случае вам нужно сначала внести изменения в файл PHP-FPM. Перейдите в /etc/php5/fpm/pool.d/www.conf (может варьироваться в зависимости от версии PHP). Установите следующую директиву:

request_terminate_timeout = 300

Затем вы должны изменить файл php.ini, который обычно расположен по адресу /etc/php.ini. Найдите директиву max_execution_time. Увеличьте ее значение до 300 или создайте директиву, если ее нет:

max_execution_time = 300

Наконец, вам нужно будет изменить файл nginx.conf. Добавьте в конфигурацию вашего виртуального хоста Nginx следующее:

location ~ .php$ {

...

fastcgi_read_timeout 300;

}

Затем просто перезапустите Nginx и PHP-FPM.

service nginx reload

service php5-fpm reload

Если вы используете Nginx в качестве прокси для Apache, то в таком случае добавьте следующее в ваш файл nginx.conf:

proxy_connect_timeout 600;

proxy_send_timeout 600;

proxy_read_timeout 600;

send_timeout 600;

Далее просто перезапустите Nginx.

service nginx reload

Заключение

Как вы можете видеть, есть много разных способов и методов устранения ошибок 504 gateway timeout на WordPress сайте. Как правило, это проблемы с сервером, и в данном случае вам нужно связаться с вашим хостингом, чтобы решить их. Но важно помнить о том, что они могут также вызываться и сторонними плагинами или переполнением очереди/бэклога ваших PHP-воркеров.

Источник: kinsta.com

fix 504 gateway timeout error in wordpress

Besides 500 and 503, 504 is one of the most common HTTP errors you can run into. As we mentioned in other articles, errors from the 500 family are the hardest to understand since the error pages are generic and don’t give you many clues about the culprit.

  • What Is the 504 Gateway Timeout Error?
  • Why Does 504 Gateway Timeout Error Occur?
  • Fix the 504 Gateway Timeout Error in WordPress

What Is the 504 Gateway Timeout Error?

A 504 error basically means that one of the servers in the network didn’t respond in the expected time, and the request sent by your browser was not returned.

Here’s what the error page might look like on your browser:

  • Error 504
  • HTTP Error 504
  • HTTP Error 504 — Gateway Timeout
  • HTTP 504
  • Gateway Timeout Error
  • 504 Error
  • Gateway Timeout (504)
  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • 504 Gateway Timeout

Why Does 504 Gateway Timeout Error Occur?

The 504 error usually occurs when the main server doesn’t get a timely response from the upstream server and times out. You may see it pop up if you’re using Cloudflare – say Cloudflare sends a request to your server and it doesn’t respond in time. In that case, Cloudflare returns the error 504 to your browser.

The issue might be down to a component in the hosting infrastructure, like the database or reverse proxy that fails to respond in time. That can cause your browser to display error 504.

Fix the 504 Gateway Timeout Error in WordPress

The 504 error could have any number of causes behind it, which is why you’ll have to try out a few troubleshooting methods in turn and see what sticks. Let’s start from the client-side.

  1. Try refreshing the browser or visiting the same URL in incognito mode.
  2. Reset your router.
  3. Check your proxy settings, and make sure it’s turned to auto-detect settings.

Debugging on the Server-side to Fix Error 504

If none of the client-side advice helped, you need to dive deeper into potential server issues to find the cause and debug.

  1. First, check the error log to see if some of the themes or plugins are wasting memory space and causing this issue. This isn’t a common cause, but it’s possible for a malfunctioning plugin to slow down the server so it cannot respond in the expected time.
  2. If step 1 doesn’t help, deactivate your CDN if you’re using one.
  3. Use a DNS Checker like whatsmydns to see if the FQDN (fully qualified domain name) resolves to the correct IP address. Flush your DNS cache.
  4. Check with your hosting provider – perhaps it’s an issue on their end – and resolve it together with them.

To make your life much easier, we have integrated Cloudflare into our infrastructure, which you can activate in the following steps.

In your application settings, click on the Cloudflare option and insert the domain name used for that application.

cloudflare option in cloudways

After enabling Cloudflare for your application, add the TXT records to confirm domain ownership. Set up these values where your DNS is handled; this is usually the place where you’ve bought the domain.

verify domain ownership

After you create these two records it will take some time for Cloudflare to confirm your domain. As soon as it’s done, create an A/CNAME record to point DNS to Cloudflare and complete activation.

Summary

Server errors can be caused by a faulty plugin or a theme, even corrupted WordPress core. However, that is not the case with 504 Gateway Timeout since it’s pointing out that the communication between two servers is not established or one of the servers didn’t respond.

Avoid losing time looking for the culprit in WordPress because that would be the last place to look.

We hope this article helped in resolving this issue and feel free to contact our support team if you ever experience it with us.

Share your opinion in the comment section.
COMMENT NOW

Share This Article

Customer Review at

“Beautifully optimized hosting for WordPress and Magento”

Arda Burak [Agency Owner]

Aleksandar Savkovic

WordPress Developer, Lecturer, the product guy interested in Agile product development. WordCamp and WP/Woo Meetup speaker and Organizer, and Community Manager at Cloudways. Also, a Formula 1 and MotoGP freak.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Thank you for your feedback!

If you’ve ever visited a website that serves you on an error page, you would have experienced how frustrating it is classified as the most frustrating thing you can do as a brand doesn’t meet your target audience’s needs and expectations. If you’re a website visitor, you would have probably viewed an error page when the users are looking for help or information. They couldn’t get frustrated and lose trust in your brand, permanently damaging your reputation.

The 504 Gateway Timeout Error is considered one type of error that can hurt the usability experience in such a manner. It will help you avoid the loss of brand sentiments and customer trust. We’ve discussed which type of error it means and the common causes and solutions to improve your website with effective technical SEO. You need to start by conducting this activity. In other words, 504 errors indicate a different computer, the one that your website is getting the message on doesn’t control. Still, it heavily relies on and isn’t communicating with it in a fast-paced environment.

What is a 504 Gateway Timeout Error?

A 504 Gateway Timeout Error can be highlighted in the internet browser window, similar to normal web pages. The 504 error highlights a problem with your network connection or server communication speed. 

When the browser sends an HTTP request to the server, it doesn’t receive a response from the upstream server in time to complete the request. Thus the request is “timed out.” Since a 504 Gateway Timeout Error is rather considered a generic format, it doesn’t actually pinpoint the exact cause of the problem. If this happens, your website will serve an error web page to your site’s visitors.

How You Might See the 504 Error?

If you are looking into individual websites are allowed to customize how they show a “gateway timeout” errors, but here are the most common ways that you’ll see one spelled out error:

  • 504 Gateway Terminal
  • HTTP 504
  • 504 ERROR
  • Gateway Timeout (504)
  • HTTP Error 504 – Gateway Timeout
  • Gateway Timeout Error

A 504 Gateway Timeout error is displayed in the internet browser window, similar to what the normal web pages do. There would be a website’s familiar headers and footers, and it seems to be a very nice English message on the page, or it could show up on an all-white page with a big 504 at the top. It shows an instinctive and identical same message, regardless of how the website happens to show it.

What are the Causes of 504 Gateway Timeout Errors

Most of the time, the question arises what does 504 gateway timeout errors  mean, it refers to whatever other server is taking so long that its “timing out” is probably down or not working properly. Since this error is based on a network error between servers on the internet or an issue with an actual server, the problem is probably with your computer, device, or internet connection. Hence, there are certain things that you can try in the case of fixing the HTTP 504 gateway timeout error.

How Do I Fix the Fix the 504 Gateway Timeout Error?

If you see a 504 Gateway timeout error, you might be confused about what to do further? You can always try the following steps:

1. Try to Reload the Page 

The foremost thing you should do when you face the HTTP Error 504 Gateway Timeout is to simply wait for a minute and reload the page. Regardless, the hosting or server merely is overloaded, and the site will quickly return to work. 

In another instance, you can easily check your website status on a specific website. This site will inform you if the site is out of service only for you or for all the visitors. The tools easily check the HTTP status code that is returned by the server. If the code differs from 200, then, in this case, you will see the done pointer. It will mean that the site doesn’t work for everyone.

2. Try a Different Browser

In such a case, the site is online, but you still see the HTTP Error 504 Gateway Timeout. You need to try changing your browser to another one. You must clear the browser cache or use the incognito mode, this can also help the user to determine if the error is caused by the browser.

3. Check on Different Devices 

Try opening the site on different computers, on different networks, or on mobile devices. If nothing could help to fix the Error 504 gateway timeout, this step will help you to determine if the problem is on the server-side or it is local.

4. Disable the Proxy

Disable the Proxy

Sometimes you might receive an HTTP 504 error code if you use a proxy server. These cases are quite rare, especially on the client-side. You need to read the guidelines on how to disable proxy on Windows and Mac.

5. Check DNS Records Propagation

Sometimes, HTTP Error 504 gateway timeout often causes a few problems with the DNS server. There are two reasons for that on the server side, it happens whenever the domain name isn’t changed to the correct IP address. If you’ve shifted the WordPress website to a new hosting domain, it’s essential to wait until the address will be implemented to the DNS base. In certain cases, it covers upto 24 hours. It merely depends on your DNS records TTL value. 

Also, you can use a freemium tool such as DNSMap to check whether your DNS has been spread across the world. The second DNS issue relates to the client-side, in this case, you can clear your local DNS cache. This is similar to clearing the browsing cache. 

In Windows, you need to simply open a command line and type the following instances

Check DNS Records

Also you should see the “Successfully flushed the DNS Resolver Cache” message.

Using the MacOS, type the following in the terminal:

  • dscacheutil -flushcache

Note: there aren’t any messages of successful functions on Mac.

Ultimately, you can temporarily change your client’s DNS servers. By default, DNS servers are provided by your Internet Service Provider. Also it enables users to temporarily change them to a public DNS server, for example provided by Google. There are certain people who usually prefer to use Google’s public DNS constantly because in certain cases that is more reliable and versatile to proceed ahead. Some people prefer to use Google’s public DNS constantly because in certain cases they are more reliable. 

6. Temporarily Disable the CDN

Also, the problem that you might relate to the content delivery network, if you use a third-party CDN provider, you can try to temporarily disable it. For that purpose, you may use WordPress plugins, with them you will be able to disable the CDN safely. If you use the backproxy services such as Cloudflare or Sucuri, they may cause the 504 gateway timeout error as they use the extra firewall. 

Mostly cache 500 state codes when they are returned by your source server, as users tend to notice the issue on Cloudflare’s freemium plan. Significantly, Cloudflare is a complete proxy service that provides you the fastest way to disconnect it. Although, before blaming cloudflare, it is essential to know that there are two type of 504 gateway timeout errors:

7. 504 Gateway Timeout in Cloudflare (Version 1)

Fix the 504 Gateway Timeout Error?

If you see a similar page like this, then in this case, the problem is on the Cloudflare side. You can contact their user support or check their status page. More particularly, they have already been notified about this problem and are working on it. 

8. 504 Gateway Timeout in Cloudflare (version 2)

504 Gateway Timeout in Cloudflare

If you see the page appearance like the above one, then this is an issue with your WordPress hosting provider. Users can follow the recommendations in the next step.

Identify the Problems with your Hosting Provider:

The servers encounter certain problems that are one of the common reasons as to why the users experience 504 errors on their WordPress website. In simple terminology, Nginx or Apache waits for a significant response until the waiting time has expired.

504 errors are classified as one of the popular onsites with a lot of visitors, online sites, and online stores. The latter may have installed popular eCommerce plugins such as WooCommerce. They would have many non-cached requests that can cause the servers to overlead. 

Although, such errors can happen to a variety of website categories that includes blogs and vice versa. Most of the hosters usually offer to upgrade to a more expensive tariff plan to sort out this problem, and even if this usually assists you to solve this issue, it is often not necessary and essential to proceed ahead.

Conclusion

Certainly, there are a variety of ways and methods to fix HTTP 504 gateway timeout errors on the WordPress site. Typically, this is an issue with the server, and in such circumstances, you need to contact your hosting provider to solve them. But it is essential to remember that they can also be caused via third-party plugins on the queue or backlog overflow for your web developers. Hence, you can know more about HTTP Status Codes via reading online.

An HTTP 504 Gateway Timeout error is the most common error encountered by website developers. And in many cases, it can become a real pain.

Generally, it’s difficult to find out the reason for a timeout error because the server response has no helpful information about the error cause.

In this article, we’ll find ways to troubleshoot timeout errors and find solutions for them, while giving you a better understanding of timeout errors and their causes.

What is a 504 Timeout error?

To deeply understand what a 504 Gateway Timeout error is let’s first have a look at server and client relationships.

What happens when the client sends an HTTP request to the server? When the server receives the request, it processes it, and–depending on whether the result is successful or unsuccessful–returns a response with the corresponding HTTP status code in the HTTP response headers.

http request and http response

HTTP status codes are a very important part of the conversation between web servers and clients.

You can find the status code in each server response. All HTTP response status codes are separated into five classes or categories. Each status code is a 3-digit number where the first digit defines the class of response, while the last two digits don’t have any classifying or categorizing role. Here is a list of status codes:

  • 1xx informational response – the request was received, and is being processed
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or can’t be fulfilled
  • 5xx server error – the server failed to fulfill an apparently valid request

If the request is processed successfully by the server it’ll return status code 2xx.

For example, the 200 status code indicates that the server understood the request and successfully processed it. A 201 status code indicates that the request was successful and, as a result, the resource has been created.

The 5xx status codes indicate that there are problems with the server. We have a 504 Gateway Timeout error when the server is running as a gateway or a proxy server. This error happens when the server can’t receive a timely response from the upstream server.

If there’s an issue in the server besides a 504 Gateway Timeout error, it often returns one of these status codes:

500 Internal Server Error

A generic error message for an unexpected condition that has no suitable specific message.

501 Not Implemented

The server either doesn’t recognize the request method, or it lacks the ability to fulfill the request.

502 Bad Gateway

The server is acting as a gateway or a proxy and receives an invalid response from the upstream server.

503 Service Unavailable

This code indicates that the server is temporarily unable to process the client’s request because it is overloaded or down for maintenance.

You can come across other 5xx unofficial codes, like 509, 526, 529, 530, 598, etc. The following codes are not specified by any standard.

504 Errors: Appearance

A 504 Gateway Timeout error can appear in different ways. Depending on the operating system, web browser, and device it may have different looks.

Some websites can customize the template of a 504 Gateway Timeout error to make it look more original and less annoying. Here’s a Google example:

Google's 504 error page

Different platforms can change the timeout error message. So you can come across different timeout messages but they all have the same meaning.

  • 504 Error
  • Gateway Timeout (504)
  • HTTP 504
  • 504 Gateway Timeout
  • Gateway Timeout Error
  • HTTP Error 504 – Gateway Timeout
  • Error 504 Gateway Timeout

What causes timeout errors?

A 504 error is a server-side error. In other words, the problem is on the server. This error can occur because of networking errors between servers.

But in very rare cases an error can be caused by client-side issues that are connected to your device or your networking device. For example when you’re trying to access a website from your computer and get a timeout error. In this case, there are some tips to solve this error from your end. We’ll go through these tips in the next section.

Client-side troubleshooting strategies

In very rare cases the cause for 504 errors is on your end. Here are very simple ways to fix it.

Reload the page

The first thing that you should do is reload the page and wait for a minute. If the timeout error disappears it means that it was a temporary problem with the actual server or the networking between servers.

Restart network devices

If reloading the page doesn’t give any result, try to restart your device and your network devices such as modem or router. After restarting the devices reload the page. If it works it means that the temporary problem was on your devices. If not try further steps.

Flush DNS cache

The problem can be from your DNS servers. Linux, Windows, and macOS save name resolution information in the form of a DNS cache. You can clear your DNS cache. For flushing cache on Windows, open Windows command prompt and type:

ipconfig /flushdns

In case of success, you have to get the ‘Successfully flushed the DNS resolver Cache’ message.

On macOS you should open the terminal and type

sudo killall -HUP mDNSResponder

There’s no message after processing this command, you can add your own, by running the command in this way

sudo killall -HUP mDNSResponder; dns cleared successfully

Cleaning a DNS cache on Linux differs from macOS and Windows. Different Linux distributions use different DNS services. Some of them are NSCD (Name Service Caching Daemon), dnsmasq, and BIND (Berkeley Internet Name Domain). Open the terminal and depending on your own Linux distribution DNS server use one of these commands to flush DNS cache on Linux:
For an NSCD DNS cache:

sudo /etc/init.d/nscd restart

For a dnsmasq DNS cache:

sudo /etc/init.d/dnsmasq restart

For a BIND DNS cache:

sudo /etc/init.d/named restart
sudo rndc restart
sudo rndc exec

If the terminal asks, enter your password. If this doesn’t help, try the next steps.

Change DNS servers

If cleaning the DNS cache didn’t help then you can change your DNS servers. When you change the DNS servers that your internet-connected device uses, you change your servers, usually assigned by your ISP. You can read this article for more information about changing DNS servers: Change your DNS servers settings.

In case you’re using Cloudflare

Cloudflare returns a 504 error and shows a screen with a 504 error custom template when your origin web server responds with a standard HTTP 504 Gateway Timeout error:

standard http 504 gateway timeout error

This is because something is wrong with your server. You can try to fix it with the steps that we’ve already described if it doesn’t help connect to your hosting provider.

If the 504 error is from Cloudflare, the screen may look like this:

Cloudfare 504 error

If the error doesn’t contain the word “Cloudflare”, it means that the problem comes from the actual server. If the error contains the word “Cloudflare”, contactCloudflare support. The same goes for 502 Bad Gateway errors. More about Cloudflare 5xx errors you can find in this article: Troubleshooting Cloudflare 5XX errors.

Server-side troubleshooting strategies

As mentioned the main reasons for 504 Timeout Errors are server-side issues. This can happen due to a variety of reasons: server-side infrastructure, limited server-side parameters, improper firewall configuration, bots, attacks, heavily working PHP scripts, or WordPress imports.

To find out the reason for 504 Timeout Errors you can check your server logs. By checking access logs you can discover if there are any spams from bots. You can also check error logs for information about issues on your website. With 10Web, you can easily do this by going to Hosting Services > Logs. You can select Access Logs, Error Logs, PHP-FPM Logs from the selection at the top of the page.

access server logs via 10Web

If you have access to your server, you can check server logs. Depending on your web server type (Nginx or Apache) the logs can be in /var/log/nginx or in /var/log/apache2 correspondingly.

Server-side infrastructure

Efficient server-side infrastructure has a huge role in avoiding 504 errors. Many shared hostings don’t provide enough resources for high-traffic websites.

That’s why contrary to shared hostings, we, at10web, provide automated WordPress hosting powered by Google Cloud, allowing us to use Linux containers to isolate the resources provided to you. In other words, the MySQL database is in a separate instance which makes lower load in instances possible; hence, there are less 504 errors. If you face a 504 error write to our customer support and the issue will be solved immediately.

Server-side parameters

The other major reason for a 504 Timeout Error is the number of PHP workers. PHP workers are background processes that are responsible for processing PHP code.

If you have only one PHP worker your site can process only one request at once. But this doesn’t mean that the second request won’t be processed. Instead, the PHP processes will be placed in a queue. Only after processing the first request the PHP processes that are next in line will be processed.

In case all PHP workers are busy and the queue is full, 504 or 502 errors may occur. So it’s very important to understand the exact number of workers that will best serve your needs. Depending on your website type (it can be a simple blog or an eCommerce platform that requires processing non-cached pages) you’ll need a different number of PHP workers. Increasing the number of workers allows your website to serve more concurrent requests.

Improper firewall configuration

Another reason for a 504 Gateway Timeout error can be improper firewall configuration.

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It typically establishes a barrier between a trusted network and an untrusted network.

In some cases, there can be awkward firewall settings that consider safe and valid content malicious and, consequently, cut off traffic which in turn can lead to 504 Timeout Errors. Check your server error logs to find out if your firewall has improper configs.

Bots & attacks

Many requests from bots or DDoS attacks by hackers may lead to performance issues in your website which can be a reason for timeout errors. To avoid this you can use Cloudflare, a market leader in DDoS protection.

3rd-party plugins & theme

Heavily working PHP scripts that are written in a non-optimal way can be the reason for timeout errors.

If you have a 504 Gateway Timeout error and find that everything is ok with your server configuration, check plugins your and the theme of your WordPress website.

Deactivate all plugins and start activating them one by one to find out the guilty ones. If you can’t open your WordPress admin dashboard because of the error but have file access to WordPress installation, just rename the plugins folder in wp-content. This will deactivate all plugins. For your theme, you can temporarily change the theme to WordPress’ default theme to discover the issue.

504 Gateway Timeout errors can occur due to cron jobs that are running on your server doing heavy tasks. For checking which crons are running, you can use the WP Control plugin which allows you to view and control what’s happening in the WP-Cron system. If you have access to wp-cli you can run this command for checking crons:

wp cron event list

The result will be:

wp-cron system to find out if it cases a 504 error

To avoid timeout errors you can configure your wp cron in a way that allows it to run like a real cron. Since wp cron works during the request it has max execution time limitation and, hence, can lead to timeout errors. Read more about this here.

Inefficient database queries can also cause timeout errors. To discover such queries you can use the Query monitor plugin, which is a developer tools panel for WordPress. It enables debugging of database queries, PHP errors, hooks and actions, block editor blocks, enqueued scripts and stylesheets, HTTP API calls, and more.

Another useful tool to find timeout errors is wp profile-command package for wp-cli.This doesn’t come with wp-cli. You have to install it yourself. It gives you profiling information about how long each step of your WordPress website loading process has taken. If you have ssh access to your website, you can easily install it by running this command

wp package install [email protected]:wp-cli/profile-command.git

More info about wp-cli you can find in this article: The Last Guide to WP CLI You’ll Ever Need.

WordPress Imports

The plugins WP All Import or WordPress Importer are widely used by WordPress developers for importing XML, CSV files and images to their websites. If the connection between the server and the client is open for a long time during import it can cause timeout errors.

To solve this problem you can try to import the file by chunk, i.e. by dividing it into smaller files. If you have access to wp-cli you can try this command for importing a file:

wp import example.wordpress.2021-03-23.xml

Server configuration

In this section let’s have a look at specific server-side parameters. Increasing these parameters can help solve 504 timeout issues.

If you want to increase max execution time for your php scripts then change the max_execution_time parameter in your php.ini file

max_execution_time = 300

The default value of max_execution_time is 30 seconds.

If your website is running with an Apache web server you can change the TimeOut directive in the httpd.conf file.

TimeOut seconds

Syntax: 
TimeOut seconds 
Default: TimeOut 300 
Context: server config, virtual host

If your website is running with a standalone Nginx web server with a FastCGI Process Manager (PHP-FPM) you can open /etc/php7.4/fpm/pool.d/www.conf and set

request_terminate_timeout = 300

If you want to increase the time limit for a given site, open the /etc/nginx/sites-available/example.com and increase the fastcgi_read_timeout directive

location ~ .php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.4-wplive.sock;
fastcgi_read_timeout 300; 
}

To increase the time limit for all sites, open the /etc/nginx/nginx.conf file and

http {
	#...
        fastcgi_read_timeout 300; 
	#...
}

After changing params don’t forget to reload PHP FPM and Nginx:

sudo service nginx reload
sudo service php7.4-fpm reload

If you’re using Nginx as a reverse proxy server for Apache then you have to change these directives in your nginx.conf file:

proxy_connect_timeout 600;

proxy_send_timeout 600;

proxy_read_timeout 600;

send_timeout 600;

After increasing params reload Nginx

sudo service nginx reload

What is ERR_CONNECTION_TIMED_OUT?

ERR_CONNECTION_TIMED_OUT means the server is taking too much time to reply.

This error appears when your website is trying to do more than your server can manage. It’s particularly common on shared hosting where your memory limit is restricted.

To fix this you can clear the browser cache or open the page in incognito/private mode. Try all steps mentioned under the section “Client-side troubleshooting”.

Increase your memory limit in wp-config.php. If you don’t have access to your server you can ask your hosting provider to increase your memory limit for you.

Increase the maximum execution time in your php.ini file as we described above or ask your hosting provider.

Cache implementation

The final step of avoiding timeout errors is using caching on your website.

Caching websites has many benefits. It improves website performance and user experience. And it reduces the load in your hosting server.

With 10Web, you can use our hosting cache, which you can enable by heading to Hosting Services > Tools > Website Caching.

website caching via 10Web to avoid a timeout error

For caching you can use different WordPress caching plugins. The popular ones are WP Rocket which improves loading time and W3 Total Cache which improves the SEO and user experience of your site. <!–More info about caching you can find here.–>

Conclusion

In this article, we explored different ways of troubleshooting and fixing a 504 Gateway Timeout error.

While there’s a variety of reasons for a timeout error, we learned that they’re generally caused by server-side problems.

But, of course, non-optimal PHP scripts and database queries and an appropriate number of PHP workers can also have a huge impact on website performance and consequently cause timeout errors.

That was all for now. Feel free to drop a comment and let us know if we managed to provide a suitable way for you to troubleshoot your timeout error!

Stuck with Cloudflare error 504? Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.

This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.

It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.

What causes error 504 gateway timeout?

Some of the main causes for the Cloudflare 504 gateway timeout error is given below:

Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.

Cloudflare Error 504

504 error originating from Cloudflare end.

Cloudflare Error 504 2

The 504 gateway timeout error at Cloudflare due to large uploads

How to fix  504 gateway timeout

We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.

  1. Fix for Receiving 504 from the origin web server

We will ensure the below aspects at the webserver:

  1. First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.
  2. Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.
  3. High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.
  4. Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.
  5. Fix for 504 error originating from Cloudflare

At times error will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.

However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.

For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:

  1. The exact time and timezone when the issue occurred
  2. URL that resulted in the HTTP 504 error as a response.
  3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads

The reason for this is the size of the uploads to the site being too large causing server timeouts.

Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.

This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.

Понравилась статья? Поделить с друзьями:
  • Ошибка 504 bad gateway что это значит
  • Ошибка 504 1с линк
  • Ошибка 503f indesign
  • Ошибка 503404 02 man
  • Ошибка 50320 shelter