Error verifying request error querying service server returns 504 code

HTTP Error 504 – 504 Gateway Timeout Status Code Explained While surfing the internet, we are able to interact with web servers through HyperText Transfer Protocol (HTTP) requests. These requests are sent from the client (our browsers) to the server before we get a response. HTTP status codes allows us know if our request […]

Содержание

  1. HTTP Error 504 – 504 Gateway Timeout Status Code Explained
  2. What Is the HTTP 504 Error?
  3. How to Fix the HTTP 504 Error
  4. Refresh Your Browser
  5. Disconnect and Reconnect Your Network Devices
  6. Clear Browser Data and Cookies
  7. Find Out If Other Users Are Experiencing the Same Problem
  8. Contact Your Hosting Provider
  9. Check for DNS Changes
  10. Conclusion
  11. Ошибка 504 Gateway Time Out — что значит почему она возникает и как ее исправить?
  12. Как можно увидеть ошибку 504 Gateway Time out
  13. Причины возникновения ошибки 504 Gateway Time out
  14. Как исправить ошибку 504 Gateway Time out
  15. Исправление ошибки 504 Gateway Time out на вашем собственном сайте
  16. Больше способов увидеть ошибку 504 Gateway Time out
  17. Ошибки похожие на 504 Gateway Time out
  18. Ошибка 504 Gateway Time Out
  19. Как исправить ошибку 504 посетителю сайта
  20. How to Fix the 504 Gateway Timeout Error on Your Site
  21. Prefer to watch the video version?
  22. What Is the 504 Gateway Timeout Error?
  23. Variations of the 504 Gateway Timeout Error
  24. SEO Impact of the 504 Gateway Timeout Error
  25. Causes of the 504 Gateway Timeout Error
  26. How to Fix the 504 Gateway Timeout Error
  27. 1. Try Reloading the Webpage
  28. 2. Reboot Your Network Devices
  29. 3. Check Your Proxy Settings
  30. 4. Check for DNS Issues
  31. 5. Disable Your Site’s CDN Temporarily
  32. 504 Gateway Timeout at Cloudflare (Variation 1)
  33. 504 Gateway Timeout at Cloudflare (Variation 2)
  34. 504 Gateway Timeout at Cloudflare Due to Large Uploads
  35. 6. Check Server Issues With Your Host
  36. Deploy your application to Kinsta — Start with a $20 Credit now.
  37. Slow Server Infrastructure
  38. Needs More PHP Workers
  39. Firewall Issues
  40. Network Connectivity Problems
  41. HTTP Timeouts
  42. 7. Check for Spam, Bots, or DDoS Attacks
  43. 8. Repair Your Corrupted WordPress Database
  44. 9. Check Your Site’s Plugins and Themes
  45. 10. Check Error Logs
  46. 11. Configure Apache or Nginx Settings Properly
  47. For Apache Webservers
  48. For Nginx Webservers
  49. Other HTTP Errors Like 504 Gateway Timeout
  50. Summary

HTTP Error 504 – 504 Gateway Timeout Status Code Explained

While surfing the internet, we are able to interact with web servers through HyperText Transfer Protocol (HTTP) requests. These requests are sent from the client (our browsers) to the server before we get a response.

HTTP status codes allows us know if our request to the server was successful or not. Here are the status codes and what each type means:

  • 100 — 199 (Informational).
  • 200 — 299 (Successful).
  • 300 — 399 (Redirection).
  • 400 — 499 (Client error).
  • 500 — 599 (Server error).

In this article, we’ll be talking about the 504 error which falls under the server error category. We’ll see some of the reasons why you might encounter this error and the possible ways of fixing it.

What Is the HTTP 504 Error?

From the status codes listed before this section, we can see that the 504 error is a server error. This means that it is not a problem from our end as the client. Our request was sent successfully to the server but something went wrong while we were awaiting a response.

You’ll usually get a response saying «Gateway Timeout Error» or something similar if it is a 504 error.

This error occurs when our server doesn’t receive a response fast enough from the server where our request was sent. As a result of the delay, our server times out and returns an error instead.

The reasons for this error can vary. The server where the request was sent to could be down for maintenance or overloaded, amongst other reasons.

How to Fix the HTTP 504 Error

In this section, we’ll talk about some of the ways in which you can fix the 504 error.

The following solutions are for users visiting websites:

Refresh Your Browser

The first thing you should try when you encounter this error is to refresh your browser. Each browser usually has a shortcut for refreshing, but you can always use the refresh button.

Disconnect and Reconnect Your Network Devices

If refreshing your browser doesn’t fix the problem then you should try disconnecting from and reconnecting to your network devices. This could be a modem, a router, a Wi-Fi hotspot, and so on.

Clear Browser Data and Cookies

Each browser has a way of clearing data and cookies but this is usually in the browser settings.

While this may fix the problem, you should know that in most cases, it doesn’t – so be sure you are willing to get rid of the data and cookies before proceeding.

Find Out If Other Users Are Experiencing the Same Problem

If you are on any community platform or know other users who make use of the website then you should probably try and find out from them to see if it is a general problem.

If this is a general problem then you can sit back and relax. The website owners might be up to something on the backend.

Note that trying these fixes above may not work all the time. In situations like this, the best thing to do is to wait and try later because it is usually not a problem from your end as the client.

The following solutions are for you if you own a website:

Contact Your Hosting Provider

In cases where the website belongs to you and users cannot access it, you should try contacting your hosting provider to be sure everything is in check.

It could be as a result of your hosting plan requiring an upgrade because you may have reached the limits of your current plan.

Check for DNS Changes

When you change servers for your website, the DNS information changes will usually take some time before updating. So you can inform your users of changes like this before or after they happen.

DNS stands for Domain Name System. They change domain names to IP addresses which browsers can easily recognize before loading websites.

Conclusion

In this article, we talked about the HTTP 504 error. We talked about HTTP status codes and found out what category the 504 error belonged to.

We then talked about why this error might happen and some of the possible ways of fixing it.

Источник

Ошибка 504 Gateway Time Out — что значит почему она возникает и как ее исправить?

Ошибка 504 Gateway Time out – это код состояния HTTP , который означает, что один сервер не получил своевременный отклик от другого сервера, к которому он обратился, пытаясь загрузить веб-страницу или выполнить запрос браузера. Она может возникать вместе с 502 Bad Gateway .

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

Как можно увидеть ошибку 504 Gateway Time out

Отдельным сайтам разрешено настраивать отображение ошибки Gateway Timeout . Вот несколько распространенных способов вывода подобной ошибки:

Ошибка 504 Gateway Time out появляется внутри окна браузера, как обычная веб-страница. На ней могут быть знакомые верхние и нижние колонтитулы сайта и красивое английское сообщение. Также подобная ошибка может отображаться на полностью белой странице с большой цифрой 504 вверху. Это одно и то же сообщение, независимо от того, как сайт показывает его вам.

Помните, что ошибка 504 Gateway Time out и 502 Bad Gateway nginx может появиться в любом браузере, операционной системе и на любом устройстве.

Причины возникновения ошибки 504 Gateway Time out

В большинстве случаев ошибка 504 Gateway Timeout означает, что любой сервер, который выдает « тайм-аут », » упал » или неправильно работает.

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

Как исправить ошибку 504 Gateway Time out

Перезагрузите веб-страницу, нажав кнопку обновление / перезагрузка, в F5 или повторив URL-адрес из адресной строки.

Несмотря на то, что 504 Gateway Timeout и ошибка 502 Bad Gateway сообщает о неподконтрольной вам ошибке, проблема может быть временной. Просто перезагрузите страницу — это быстро и легко.

  • Перезапустите все сетевые устройства. Временные проблемы с модемом, маршрутизатором, коммутаторами или другим сетевым оборудованием могут вызывать ошибку 504 Gateway Timeout . Простой перезапуск этих устройств может помочь.

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

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

Подсказка . Смотрите Proxy.org обновленный, проверенный список прокси-серверов, которые можно использовать.

Примечание . Большинство компьютеров не имеют настроек прокси-сервера, поэтому, если ваши настройки пусты, пропустите этот шаг.

  • Измените DNS-сервер. Возможно, ошибка 504 Gateway Timeout , которую вы видите, вызвана проблемой с DNS-сервером , который вы используете.

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

Подсказка . Если не все сетевые устройства получают ошибку HTTP 504 или 502 error Bad Gateway , но все они находятся в одной сети, изменение DNS-сервера не сработает. Если это похоже на вашу ситуацию, переходите к следующей идее.

  • Если изменений не произошло, обратитесь к сайту. Это единственное, что вы можете сделать. Велика вероятность, что администраторы сайта уже работают, чтобы исправить первопричину ошибки 504 Gateway Timeout .

На большинстве сайтов есть учетные записи социальных сетей, которые они используют для поддержки. А некоторые даже имеют номера телефонов и адреса электронной почты.

Подсказка . Если начинает казаться, что сайт выдает 504 ошибку для всех, поищите в Twitter в режиме реального времени информацию о недоступности сайта. Лучший способ сделать это — найти #websitedown в Twitter . Например, если Facebook может быть недоступен, выполните поиск по тегу #facebookdown .

  • Обратитесь к своему интернет-провайдеру. Вероятнее всего, что после описанного выше устранения неполадок, выскакивающая 504 Gateway Timeout — это проблема, вызванная неполадками в Сети, за которую отвечает ваш провайдер.
  • Вернуться позже. На данный момент вы исчерпали все варианты, и ошибка 504 Gateway Timeout устраняется администратором сайта или интернет-провайдером.

Регулярно проверяйте сайт. Без сомнения, он снова начнет работать.

Исправление ошибки 504 Gateway Time out на вашем собственном сайте

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

Большие объемы трафика могут привести к тому, что ваш сервер будет выдавать ошибку 504 . Хотя 503 или ошибка 502 Bad Gateway будет более вероятна.

В частности, в WordPress сообщение 504: Gateway Timeout иногда возникает из-за поврежденных баз данных. Установите WP-DBManager и попробуйте применить функцию « Восстановить БД », а затем « Оптимизировать БД ». Посмотрите, поможет ли это.

Убедитесь, что ваш файл HTACCESS правильный. Особенно если вы только что переустановили WordPress .

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

Больше способов увидеть ошибку 504 Gateway Time out

Ошибка Gateway Timeout при получении в Windows Update генерирует код ошибки 0x80244023 или сообщение WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT .

В программах на базе Windows , которые изначально обращаются к интернету, ошибка 504 может отображаться в небольшом диалоговом окне или окне с ошибкой HTTP_STATUS_GATEWAY_TIMEOUT и/или сообщение The request was timed out waiting for a gateway ( истекло время ожидания запроса для шлюза ).

Менее распространенная ошибка 504 — это Gateway Time-out: The proxy server did not receive a timely response from the upstream server ( прокси-сервер не получил своевременного ответа от вышестоящего сервера ), но поиск и устранение неисправностей ( указанных выше ) продолжается.

Ошибки похожие на 504 Gateway Time out

Ряд сообщений об ошибках аналогичен ошибке 504 Gateway Timeout , поскольку все они происходят на стороне сервера. Некоторые включают в себя ошибку 500 Internal Server (« Внутренняя ошибка сервера »), ошибку 502 Bad Gateway ( что это означает — «Неверный шлюз» ), и ошибку 503 Service Unavailable (« Сервис временно недоступен »), среди нескольких других.

Существуют также коды статуса HTTP , которые не являются серверными, а возникают на клиентской стороне. Например, часто встречающаяся ошибка 404 Not Found (« Страница не найдена »).

ВЛ Виктория Лебедева автор-переводчик статьи « 504 Gateway Timeout Error »

Источник

Ошибка 504 Gateway Time Out

Код ошибки в формате 5хх говорит о том, что на стороне сервера есть проблема: сервер не может обработать запрос от клиента. Клиентом в данном случае выступает браузер.

Ошибка 504 Gateway Time Out возникает, когда в заданный промежуток времени сервер не получает ответ от другого сервера, при этом другой сервер выполняет роль прокси или шлюза.

Ошибка 504 что значит

Какие ещё бывают варианты отображения ошибки:

  • HTTP Error 504,
  • Gateway Timeout Error,
  • HTTP Error 504 – Gateway Timeout,
  • 504 Gateway Timeout nginx,
  • 504 Gateway Time-out – The server didn’t respond in time,
  • Ошибка 504 Время ответа сервера истекло,
  • Время ожидания шлюза (504),
  • Ошибка тайм-аута шлюза,
  • HTTP 504,
  • 504 Ошибка.

В этой статье мы расскажем, как устранить код ошибки 504.

Как исправить ошибку 504 посетителю сайта

Итак, вы перешли на сайт, но вместо веб-страницы видите сообщение с кодом 504.

Что такое тайм аут шлюза

Проблема может быть как со стороны сайта, так и со стороны устройства, например настроек браузера. Чтобы убедиться в том, что настройки браузера в порядке:

1) Обновите страницу. Но обновите не клавишей F5, а выделите содержимое адресной строки и нажмите Enter. Если после этих действий ошибка 504 не возникает ни на текущем, ни на любом другом сайте – её можно проигнорировать.

2) Зайдите на тот же ресурс через другой браузер. Если в этом случае сайт открылся корректно, перейдите к следующему пункту.

3) Очистите кэш браузера и удалите файлы cookie. После этого браузер будет работать быстрее. Воспользуйтесь инструкцией Как очистить кэш браузера.

4) Перезагрузите роутер или модем. Отключите устройство от сети примерно на 10 минут.

5) Очистите кэш DNS. Для этого воспользуйтесь инструкцией ниже.

В зависимости от вашей операционной системы очистите кэш по одной из инструкций.

Источник

How to Fix 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. 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!

Prefer to watch the video version?

Need to give a shoutout here. Kinsta is amazing, I use it for my personal website. The support is rapid and outstanding, and their servers are the fastest for WordPress.

Phillip Stemann

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.

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 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).

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.

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

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

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

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

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

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

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:

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:

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.

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

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

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

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

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:

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

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

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.

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.

Deploy your application to Kinsta — Start with a $20 Credit now.

Run your Node.js, Python, Go, PHP, Ruby, Java, and Scala apps, (or almost anything else if you use your own custom Dockerfiles), in three, easy steps!

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.

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 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

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

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

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.

Struggling with downtime and WordPress issues? Kinsta is the hosting solution designed with performance and security in mind! Check out our plans

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

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.

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 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:

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

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:

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:

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:

Next, set the following directive:

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.

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

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

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:

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:

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.

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.

Источник

Ошибка 504 Gateway Time out – это код состояния HTTP, который означает, что один сервер не получил своевременный отклик от другого сервера, к которому он обратился, пытаясь загрузить веб-страницу или выполнить запрос браузера. Она может возникать вместе с 502 Bad Gateway.

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

  • Как можно увидеть ошибку 504 Gateway Time out
  • Причины возникновения ошибки 504 Gateway Time out
  • Как исправить ошибку 504 Gateway Time out
  • Исправление ошибки 504 Gateway Time out на вашем собственном сайте
  • Больше способов увидеть ошибку 504 Gateway Time out
  • Ошибки похожие на 504 Gateway Time out

Отдельным сайтам разрешено настраивать отображение ошибки Gateway Timeout. Вот несколько распространенных способов вывода подобной ошибки:

504 Gateway Timeout
HTTP 504
504 ERROR
Gateway Timeout (504)
HTTP Error 504 - Gateway Timeout
Gateway Timeout Error

Ошибка 504 Gateway Time out появляется внутри окна браузера, как обычная веб-страница. На ней могут быть знакомые верхние и нижние колонтитулы сайта и красивое английское сообщение. Также подобная ошибка может отображаться на полностью белой странице с большой цифрой 504 вверху. Это одно и то же сообщение, независимо от того, как сайт показывает его вам.

Помните, что ошибка 504 Gateway Time out и 502 Bad Gateway nginx может появиться в любом браузере, операционной системе и на любом устройстве.

В большинстве случаев ошибка 504 Gateway Timeout означает, что любой сервер, который выдает «тайм-аут», «упал» или неправильно работает.

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

Перезагрузите веб-страницу, нажав кнопку обновление / перезагрузка, в F5 или повторив URL-адрес из адресной строки.

Несмотря на то, что 504 Gateway Timeout и ошибка 502 Bad Gateway сообщает о неподконтрольной вам ошибке, проблема может быть временной. Просто перезагрузите страницу — это быстро и легко.

  • Перезапустите все сетевые устройства. Временные проблемы с модемом, маршрутизатором, коммутаторами или другим сетевым оборудованием могут вызывать ошибку 504 Gateway Timeout. Простой перезапуск этих устройств может помочь.

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

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

Подсказка. Смотрите Proxy.org обновленный, проверенный список прокси-серверов, которые можно использовать.

Примечание. Большинство компьютеров не имеют настроек прокси-сервера, поэтому, если ваши настройки пусты, пропустите этот шаг.

  • Измените DNS-сервер. Возможно, ошибка 504 Gateway Timeout, которую вы видите, вызвана проблемой с DNS-сервером, который вы используете.

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

Подсказка. Если не все сетевые устройства получают ошибку HTTP 504 или 502 error Bad Gateway, но все они находятся в одной сети, изменение DNS-сервера не сработает. Если это похоже на вашу ситуацию, переходите к следующей идее.

  • Если изменений не произошло, обратитесь к сайту. Это единственное, что вы можете сделать. Велика вероятность, что администраторы сайта уже работают, чтобы исправить первопричину ошибки 504 Gateway Timeout.

На большинстве сайтов есть учетные записи социальных сетей, которые они используют для поддержки. А некоторые даже имеют номера телефонов и адреса электронной почты.

Подсказка. Если начинает казаться, что сайт выдает 504 ошибку для всех, поищите в Twitter в режиме реального времени информацию о недоступности сайта. Лучший способ сделать это — найти #websitedown в Twitter. Например, если Facebook может быть недоступен, выполните поиск по тегу #facebookdown.

  • Обратитесь к своему интернет-провайдеру. Вероятнее всего, что после описанного выше устранения неполадок, выскакивающая 504 Gateway Timeout — это проблема, вызванная неполадками в Сети, за которую отвечает ваш провайдер.
  • Вернуться позже. На данный момент вы исчерпали все варианты, и ошибка 504 Gateway Timeout устраняется администратором сайта или интернет-провайдером.

Регулярно проверяйте сайт. Без сомнения, он снова начнет работать.

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

Большие объемы трафика могут привести к тому, что ваш сервер будет выдавать ошибку 504. Хотя 503 или ошибка 502 Bad Gateway будет более вероятна.

В частности, в WordPress сообщение 504: Gateway Timeout иногда возникает из-за поврежденных баз данных. Установите WP-DBManager и попробуйте применить функцию «Восстановить БД», а затем «Оптимизировать БД». Посмотрите, поможет ли это.

Убедитесь, что ваш файл HTACCESS правильный. Особенно если вы только что переустановили WordPress.

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

Ошибка Gateway Timeout при получении в Windows Update генерирует код ошибки 0x80244023 или сообщение WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT.

В программах на базе Windows, которые изначально обращаются к интернету, ошибка 504 может отображаться в небольшом диалоговом окне или окне с ошибкой HTTP_STATUS_GATEWAY_TIMEOUT и/или сообщение The request was timed out waiting for a gateway (истекло время ожидания запроса для шлюза).

Менее распространенная ошибка 504 — это Gateway Time-out: The proxy server did not receive a timely response from the upstream server (прокси-сервер не получил своевременного ответа от вышестоящего сервера), но поиск и устранение неисправностей (указанных выше) продолжается.

Ряд сообщений об ошибках аналогичен ошибке 504 Gateway Timeout, поскольку все они происходят на стороне сервера. Некоторые включают в себя ошибку 500 Internal ServerВнутренняя ошибка сервера»), ошибку 502 Bad Gateway (что это означает — «Неверный шлюз»), и ошибку 503 Service UnavailableСервис временно недоступен»), среди нескольких других.

Существуют также коды статуса HTTP, которые не являются серверными, а возникают на клиентской стороне. Например, часто встречающаяся ошибка 404 Not FoundСтраница не найдена»).

Чтобы на веб-странице появился контент, браузер должен получить от сервера, на котором расположен сайт, необходимые данные. Когда на устройстве пользователя, на веб-сервере или на другом промежуточном узле (например, прокси) возникают неполадки, вместо содержимого сайта в браузере появляется страница с ошибкой. Для устранения сбоя, необходимо знать, на чьей стороне он произошел и по какой причине. Понять, что является источником проблемы, помогает цифровой код ошибки. Если он имеет формат 5xx, значит, сбой происходит на стороне сервера. Разбираем в статье ошибку 504 на сайте и способы ее устранения.

Что значит ошибка 504 и когда она появляется

Ошибка 504 Gateway Time Out — это ошибка, возникающая при загрузке сайта, если запрос пользователя передавался на сервер, хранящий данные веб-ресурса, через промежуточный сервер, действующий как шлюз или прокси, и в процессе обработки данного запроса один из серверов не получил ответ от другого в течение максимально допустимого времени ожидания. Обмен данными происходит по HTTP, и если возникает «тайм-аут шлюза», браузер показывает на веб-странице код 504, указывающий на соответствующее состояние протокола.

Ошибка 504 Gateway Time Out.

Изображение от Freepik.

На выполнение некоторых операций на сервере выделяется определенное количество времени. Например, обработка http-запроса на Nginx по умолчанию должна быть завершена за 30 секунд. Лимит времени устанавливается для того, чтобы при избыточной нагрузке сервер мог прервать процесс, который не может выполнить, и перейти к следующей задаче. Средняя продолжительность загрузки сайта составляет всего 1–3 секунды, однако иногда она может увеличиваться, например, если сервер выполняет ресурсоемкие скрипты. Когда на это требуется больше максимально допустимого времени, соединение с клиентом (браузером) разрывается и возникает один из вариантов сообщения «HTTP Error 504 — Gateway Timeout». К повышенной нагрузке на сервер могут привести внутренние сбои на сайте, проблемы с безопасностью, настройки браузера и так далее.

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

Как исправить ошибку 504 владельцу сайта

Чтобы исправить ошибку 504, необходимо установить и устранить причину ее возникновения. Некоторые способы решения проблемы требуют вмешательства администратора сайта.

Долго обрабатывается скрипт

Если скрипт тяжелый, сервер может не успеть полностью его обработать до появления ошибки. Лучшим решением проблемы будет облегчение скрипта или его замена. Когда это невозможно, увеличивают период ожидания сервера. Лимит времени, за которое скрипт должен быть отработан, устанавливается через директиву «max_execution_time» в файле «php.ini». По умолчанию он составляет 30 секунд. Чтобы он стал больше, необходимо открыть файл и подставить в строку «max_execution_time = 30» новую допустимую продолжительность операции. Кроме того, поменять настройки можно в Nginx и Apache.

Нестандартные параметры времени ожидания сервера могут понадобиться, если вы используете Nginx в качестве прокси-сервера для Apache. Изменение времени выполнения скрипта на веб-сервере производится в файле «nginx.conf». Порядок действий:

  1. Подключение к серверу по Secure Shell (протоколу для удаленного управления операционной системой).
  2. Ввод команды «sudo nano/etc/nginx/nginx.conf» для запуска файла.
  3. Редактирование блока server: увеличение времени до наступления тайм-аута с 300 секунд до 600:

    Изменение времени выполнения скрипта в файле «nginx.conf».

  4. Перезагрузка веб-сервера командой «service nginx reload».

Коррекцию файлов «php.ini» и «nginx.conf» лучше проводить совместно. В обоих документах необходимо указать одинаковое время обработки запроса.

При использовании Apache время обработки запроса редактируется через «httpd.conf». Что необходимо сделать:

  1. Открыть файл.
  2. Ввести строку:

    Через httpd.conf.

  3. Сохранить корректировки и заново запустить сервер.

Проблемы с CDN

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

Иногда ошибка 504 может возникать при использовании CDN. Если после отключения от системы работоспособность сайта восстановится, сообщите о проблеме разработчикам сервиса.

Выросла нагрузка на один из серверов

К повышенной нагрузке на сервер может привести резкий рост трафика. Наплыв пользователей может быть связан как с намеренными действиями владельца веб-ресурса — с запуском рекламной кампании, так и со случайными событиями — временным увеличением спроса на сезонный товар, продающийся в интернет-магазине. Поскольку количество операций, которое сервер может выполнять одновременно, ограничено его вычислительной мощностью, при избыточной нагрузке хостинг-компьютер перестает отвечать на запросы пользователей. Чтобы он снова мог отдавать данные браузеру, достаточно арендовать компьютер с более мощным железом, например, с виртуального хостинга перейти на VPS. Если планируется проведение маркетинговых мероприятий, лучше заранее арендовать дополнительные вычислительные ресурсы (оперативную память, место на жестком диске и т. д.).

В компании «Интернет Хостинг Центр» клиенты могут арендовать VPS сервер в России с бесплатной защитой от DDoS на всех тарифах. Выделенный IP и техподдержка входят в стоимость.

Проверка службы DNS

Сообщение «Error 504 — Gateway Timeout» может появиться, если DNS-служба не справилась с преобразованием доменного имени в IP-адрес. Причиной ошибки становится перенос веб-ресурса с локального ПК на веб-сервер и автоматически пропадет, после того как новые DNS-данные распространяются по всему Интернету. Процесс занимает около двух суток.

Проблемы с DNS могут возникнуть на компьютере пользователя. Для их устранения на ПК вызывается командная строка операционной системы, где вводится специальная команда для очистки DNS-кэша, в Windows — это «ipconfig /flushdns».

Очистка DNS-кэша.

Спам, вирусы и DDoS-атаки

Перегрузка сервера может быть вызвана не только возросшим интересом пользователей к вашим товарам и услугам, но и менее позитивными причинами — спамом, вирусами и DDoS-атаками. Для защиты веб-ресурса от вредоносных программ и действий хакеров, необходимо предпринять несколько профилактических мер:

  • проверить наличие антивируса в административной панели хостинга;
  • включить защиту от DDoS;
  • подключить анти-спам плагины в CMS сайта;
  • проверить лог-файлы на наличие часто повторяющихся IP-адресов;
  • установить SSL/TLS;
  • защитить формы обратной связи с помощью капчи;
  • предотвратить публикацию комментариев со ссылками на вредоносное ПО, подключив модерирование контента и так далее.

Проблемы с плагинами в CMS

Функции на сайте, созданном с помощью CMS, реализуются благодаря плагинам. Не все они работают достаточно быстро, некоторые из них обрабатываются медленно, что приводит к тайм-ауту шлюза. Чтобы проверить, не является ли установленный плагин причиной сбоя, его необходимо отключить, а затем запустить сайт без него. Если веб-ресурс загрузится, значит, нужно выбрать другой функциональный модуль.

Как решить проблему, если вы — пользователь

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

  • обновите страницу, заново указав URL в адресной строке и нажав кнопку ввода (Enter);
  • откройте сайт в другом браузере, если в нем сбой не повторится, обновите браузер с ошибкой до последней версии;
  • запустите веб-ресурс на другом устройстве, чтобы проверить, не связаны ли проблемы с программным обеспечением вашего компьютера;
  • очистите файлы кэша и cookies, чтобы избавиться от ошибок, накопленных браузером за длительное время использования;
  • перезагрузите роутер, чтобы устранить конфликт между обновленным ПО провайдера и вашим устройством;
  • очистите кэш DNS через командную строку ОС.

Заключение

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

Ошибка 504 Gateway Timeout (от англ. «тайм-аут шлюза») — это код состояния HTTP, который указывает на то, что веб-сервер не получил своевременного ответа от вышестоящего сервера при попытке загрузить страницу. Простыми словами, ошибка 504 Gateway Timeout — это свидетельство о сбое на сервере, когда он выступает шлюзом или в качестве прокси.

В нашей статье клиент — браузер, а сервер — специализированная или выделенная машина.

Как выглядит ошибка 504

В зависимости от конфигурации у ошибки 504 есть различные формы написания:

  • 504 Error.
  • «Время ответа сервера истекло».
  • HTTP Error 504.
  • «Ошибка таймаута шлюза».
  • Gateway timeout.
  • The server didn’t respond in time.

Точный текст ошибки зависит от того, какой именно сервер используется в качестве фронта и какой в качестве бэка. Самые частые сценарии — Nginx и Apache, соответственно.

Один из возможных вариантов ошибки

Один из возможных вариантов ошибки

Почему возникает ошибка 504

Самая популярная причина — перегрузка сервера. Давайте посмотрим, почему она происходит и какие источники встречаются наиболее часто.

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

Ошибки от плагинов

Многие веб-мастера устанавливают большое количество разнообразных плагинов для расширения функционала сайта. Например, для внедрения кеширования страниц или добавления на сайт CDN (сеть доставки контента). Подобные плагины могут загружать данные со сторонних источников — например, удаленных серверов. Если на таком сервере возникает сбой, определенная страница или сайт целиком может начать отдавать 504-ю ошибку.

Ошибки от скриптов

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

Аномальное увеличение посещаемости

Если на сайте резко увеличивается трафик, сервер может работать медленнее. Чем больше трафика, тем больше запросов к серверу. Со временем количество неотвеченных запросов только увеличивается, в итоге взаимодействие с сервером прекращается и отправляется код состояния 504 Bad Gateway.

Небольшие скачки посещаемости не представляют угрозы для производительности сервера

Небольшие скачки посещаемости не представляют угрозы для производительности сервера

Израсходование лимитов тарифного плана хостинга

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

Пример лимитов по серверным ресурсам на начальном тарифе хостинга Beget

Пример лимитов по серверным ресурсам на начальном тарифе хостинга Beget

Загрузка на сайт файлов

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

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

Хакерские атаки

504 ошибку могут вызывать различные атаки на сайт — например, распределенная атака типа «отказ в обслуживании». Чтобы диагностировать эту причину — обратитесь в поддержку хостинга. Если атака подтвердится — установите на сайт защитный экран, например Cloudflare.

Схема атаки типа denial-of-service

Схема атаки типа denial-of-service

Вредоносный код в файлах сайта

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

Браузер Google Chrome не позволит открыть сайт, если он заражен вирусом или содержит иное вредоносное ПО

Браузер Google Chrome не позволит открыть сайт, если он заражен вирусом или содержит иное вредоносное ПО

Ошибка в браузере

В редких случаях код ответа 504 может свидетельствовать о некорректной работе браузера. Например, у вас отключен JavaScript или в кэше накопилось большое количество ошибок. Все это может привести к тому, что страница не будет загружаться корректно. Попробуйте сменить браузер или устройство и откройте проблемную страницу. Если получилось, то это именно ваш сценарий.

Как исправить ошибку 504 вебмастеру

Теперь рассмотрим, как решить ошибку самостоятельно. Отдельно пользователю и отдельно вебмастеру.

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

  1. Во первых: нужно обратиться в саппорт используемого хостинга и уточнить, не превышены ли лимиты по использованию ресурсов серверного железа на вашем аккаунте. Если вы укладываетесь в ограничения выбранного тарифного плана, то нужно искать другой источник появления 504-й.
  2. Во вторых: вспомните, какие глобальные изменения вы делали на сайте в последнюю неделю или две. Возможно вы меняли тему (дизайн) сайта, глобальный вид URL или устанавливали какие-либо плагины.

Если вы вспомнили конкретное изменение, просто откатитесь к предыдущей версии: например, удалите плагин или верните старую тему сайта.

«У меня VPS с Nginx / Apache»

С такой конфигурацией сервера возникновение 504 ошибки встречается довольно часто. Чтобы устранить ее, найдите конфигурационный файл сервера, который называется httpd.conf. Находится он в дистрибутиве Apache, соответственно. Что нужно сделать:

  1. Устанавливаем значение тайм-аута на 700 секунд и сохраняем файл. Перезагружаем бэкенд (для этого используем команду service nginx reload) и проверяем, ушла ошибка или нет.
  2. Находим файл php.ini. Открываем его и изменяем значение максимального времени исполнения на 300 секунд. Опять перезагружаем backend (используем команду service nginx reload) и проверяем, ушла ошибка или нет.

Параметр для значения Timeout устанавливаем на 700 секунд, а max_execution_time изменяем на 300 секунд

Параметр для значения Timeout устанавливаем на 700 секунд, а max_execution_time изменяем на 300 секунд

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

Изменение портов в панели управления хостингом

Также попробуйте изменить порты для обращения к сайту. Так вы решите проблему в случаях, когда выполнение скрипта занимает продолжительное время (более 30 секунд). В разных панелях управления хостингом нужно устанавливать разные порты. Например в Plesk — это 8080, в ISPManager — 8081.

Примеры портов для Plesk

Примеры портов для Plesk

«У меня на сайте используются CDN: что делать»

Выше мы уже говорили о том, что кэширующий сервер может стать причиной длительного ожидания ответа от главного сервера. Чтобы решить эту проблему, отключите сеть доставки содержимого на своем сайте. После этого очистите кэш сайта и попробуйте открыть проблемную страницу. Если ошибку 504 вызывал CDN, то страница сразу откроется.

Два типа дистрибуции контента сайта. CDN справа

Два типа дистрибуции контента сайта. CDN справа

Перенос сайта на другую сетевую конфигурацию

Если изменить значение максимального времени исполнения в php.ini для вас затруднительно, вы можете просто перейти на облачный тариф хостинга. В облачной инфраструктуре доступно тонкое управление параметрами сервера, включая регулировку технических ограничений.

Пример конфигураций облачных серверов у Selectel

Пример конфигураций облачных серверов у Selectel

Включите журналирование ошибок

Этот способ поможет точно установить, в каком именно месте происходит ошибка, не позволяющая открыть страницу. В CMS журналирование может активироваться разными способами. Например, на WordPress необходимо открыть файл wpconfig.php и добавить в него три PHP-константы для установки отладки:

define( ‘wp_debug’, true );

define( ‘wp_debug_log’, true );

define( ‘wp_debug_display’, false );

Сохраняем wpconfig.php. Все, теперь логирование ошибок включено и вы сможете посмотреть источник ошибки в журнале.

«У меня веб-сервер nginx: что делать»

В дистрибутиве сервера найдите конфигурационный файл тайм-аута и измените значения для времени:

  • таймаута для отправки прокси;
  • тайм-аута для чтения прокси;
  • времени отправки тайм-аута.

Мы установили значение для каждого вышеописанного параметра на 750 секунд

Мы установили значение для каждого вышеописанного параметра на 750 секунд

Обычно конфигурационный файл тайм-аута находится в следующей директории:

Найдите конфигурационный файл Nginx по этому пути

Найдите конфигурационный файл Nginx по этому пути

Важно: перед открытием конфигурационного файла обязательно подключитесь по протоколу SSH.

Если вы используете VPS, необязательно вручную искать конфигурационный файл, чтобы изменить значение параметров. Просто откройте административную панель сервера, найдите настройки сервера и добавьте необходимые значения. Как правило, настройки php.ini и параметры httpd всегда разнесены по разным вкладкам. Справедливо это для ISPmanager, Ajenti, Vesta Control Panel и других популярных панелей управления сервером, например, CentOS Web Panel.

Неполадки сервера

Создайте тикет в саппорте хостинга и уточните, существуют ли на данный момент какие-либо неполадки с сервером. Это довольно редкий сценарий, но проверить его также необходимо, если ошибку не удалось устранить вообще никакими из вышеописанных способов.

Пример обращения в саппорт хостинга

Пример обращения в саппорт хостинга

Как исправить ошибку 504 пользователю

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

Очистка DNS

Очистите кэш DNS в используемой операционной системе:

  • На macOS необходимо открыть «Терминал» и указать команду sudo killall -HUP mDNSResponder.
  • На Windows нужно открыть командную строку и ввести команду: ipconfig /flushdns.

Очистка сопоставителя DNS в Windows 10

Очистка сопоставителя DNS в Windows 10

Другие способы

Если очистка DNS-кэша не помогла, попробуйте выполнить следующие действия

  1. Обновите страницу с очисткой ее кэша. Для этого используется сочетание горячих клавиш Control + F5. В редких случаях в кэше могут накапливаться ошибки, особенно если вы часто посещали сайт, на котором теперь возникает ошибка.
  2. Попробуйте открыть проблемную страницу с другого устройства. В редких случаях в системе могут накапливаться ошибки, которые препятствуют открытию всего сайта или конкретной страницы. Диагностировать эту причину и поможет смена устройства.
  3. Удалите временные файлы браузера, включая кэш-файлы и файлы-куки.

В Google Chrome удалить файлы cookie и другие данные сайта, можно в разделе Конфиденциальность и безопасность

В Google Chrome удалить файлы cookie и другие данные сайта, можно в разделе Конфиденциальность и безопасность

Заключение: профилактика появления Gateway timeout для вебмастера

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

  • Какие ресурсы серверного железа вы планируете использовать.
  • Что хотите настраивать.
  • Наличие каких технологий для вас является критически важным.

Так вы сможете выбрать максимально подходящий и быстрый сервер под свои задачи. Ну а 504 ошибка точно не будет появляться на сайте.

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!

Перейти к содержанию

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

Другими словами, ошибка 504 обычно указывают на то, что другой компьютер, на котором веб-сайт, на котором вы получаете сообщение 504, не контролирует, а полагается на него и недостаточно быстро связывается с ним.

Вы вебмастер? Обратитесь к разделу « Исправление ошибок 504 на вашем собственном сайте » далее по странице, чтобы узнать о некоторых вещах, которые стоит попробовать.

Ошибка 504 Gateway Timeout может появиться в любом интернет-браузере, в любой операционной системе и на любом устройстве. Это означает, что возможно получить ошибку 504 Gateway Timeout на вашем телефоне или планшете на Android или iPhone, в Safari на Mac, в Chrome на Windows 10 (или 8, или 7, …) и т. д.

Содержание

  1. Как вы могли увидеть ошибку 504
  2. Причины ошибок 504 Gateway Timeout
  3. Больше способов увидеть ошибку 504
  4. Ошибки типа 504 Gateway Timeout

Как вы могли увидеть ошибку 504

Отдельные веб-сайты могут настраивать отображение ошибок «тайм-аут шлюза», но вот наиболее распространенные ошибки, которые вы увидите:

  • Ошибка 504 Время ответа сервера истекло
  • HTTP 504
  • 504 ОШИБКА
  • Время ожидания шлюза (504)
  • Ошибка HTTP 504 – Тайм-аут шлюза
  • Ошибка тайм-аута шлюза

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

Причины ошибок 504 Gateway Timeout

В большинстве случаев ошибка 504 Gateway Timeout означает, что «тайм-аут» сервера вероятно не работает или работает неправильно.

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

Тем не менее, есть несколько способов исправления 504 ошибки, которые вы можете попробовать:

  • Попробуйте перезагрузить страницу нажав кнопку обновления / перезагрузки, или нажав клавишу F5 или еще раз попробовав ввести URL в адресную строку браузера.

Даже несмотря на то, что ошибка 504 Gateway Timeout сообщает об ошибке вне вашего контроля, эта ошибка может быть только временной.

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

Больше способов увидеть ошибку 504

Ошибка тайм-аута шлюза при получении в Центре обновления Windows создает код ошибки 0x80244023 или сообщение WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT .

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

Менее распространенная ошибка 504 – время ожидания шлюза: прокси-сервер не получил своевременного ответа от вышестоящего сервера , но устранение неполадок (см. Выше) остается тем же.

Ошибки типа 504 Gateway Timeout

Ряд сообщений об ошибках аналогичен ошибке 504 Gateway Timeout, поскольку все они появляются на стороне сервера. Некоторые включают в себя Ошибку 500 Internal Server, в Bad Gateway 502 ошибку, и Unavailable 503 Service ошибку, среди нескольких других.

Существуют также коды состояния HTTP, которые не на стороне сервера, а на стороне клиента , как обычно встречающаяся ошибка 404 Not Found .

Просмотров 4.6к.
Обновлено 29.03.2020

Код ошибки в формате 5хх говорит о том, что на стороне сервера есть проблема: сервер не может обработать запрос от клиента. Клиентом в данном случае выступает браузер.

Ошибка 504 Gateway Time Out возникает, когда в заданный промежуток времени сервер не получает ответ от другого сервера, при этом другой сервер выполняет роль прокси или шлюза.




Ошибка 504 что значит

Какие ещё бывают варианты отображения ошибки:

  • HTTP Error 504,
  • Gateway Timeout Error,
  • HTTP Error 504 – Gateway Timeout,
  • 504 Gateway Timeout nginx,
  • 504 Gateway Time-out – The server didn’t respond in time,
  • Ошибка 504 Время ответа сервера истекло,
  • Время ожидания шлюза (504),
  • Ошибка тайм-аута шлюза,
  • HTTP 504,
  • 504 Ошибка.

В этой статье мы расскажем, как устранить код ошибки 504.

Как исправить ошибку 504 посетителю сайта

Итак, вы перешли на сайт, но вместо веб-страницы видите сообщение с кодом 504.




Что такое тайм аут шлюза

Проблема может быть как со стороны сайта, так и со стороны устройства, например настроек браузера.
Чтобы убедиться в том, что настройки браузера в порядке:

1) Обновите страницу. Но обновите не клавишей F5, а выделите содержимое адресной строки и нажмите Enter. Если после этих действий ошибка 504 не возникает ни на текущем, ни на любом другом сайте – её можно проигнорировать.

2) Зайдите на тот же ресурс через другой браузер. Если в этом случае сайт открылся корректно, перейдите к следующему пункту.

3) Очистите кэш браузера и удалите файлы cookie. После этого браузер будет работать быстрее.
Воспользуйтесь инструкцией Как очистить кэш браузера.

4) Перезагрузите роутер или модем. Отключите устройство от сети примерно на 10 минут.

5) Очистите кэш DNS. Для этого воспользуйтесь инструкцией ниже.


Как очистить кэш DNS

В зависимости от вашей операционной системы очистите кэш по одной из инструкций.

1) Откройте командную строку. Для этого введите в поисковую строку «Командная строка» и выберите появившееся приложение:




2) Введите команду:

3) Дождитесь сообщения об очистке кэша:




1) Откройте терминал клавишами Ctrl+Alt+T.

2) Введите команду:

Для Ubuntu:

sudo service network-manager restart

Для других дистрибутивов:

sudo /etc/init.d/nscd restart

1) Войдите в терминал. Для этого нажмите клавиши Command + Space. Введите Терминал и нажмите на найденное приложение.

2) Введите команду:

sudo killall -HUP mDNSResponder

Готово, вы очистили кэш DNS.

6) Обратитесь в техподдержку вашего интернет-провайдера. Возможно, это проблема сети, за которую отвечает провайдер.

Если эти действия не принесли результата – обратитесь в техническую поддержку сайта.

Если вы владелец сайта

Как исправить ошибку 504 на виртуальном хостинге

1 способ

Эта ошибка может возникнуть в случае, если для Nginx был превышен лимит на время ответа сайта. По умолчанию это 30 секунд, при этом среднее время загрузки сайта не должно превышать 1-3 секунды.
Если скрипты вашего сайта должны исполняться дольше 30 секунд, вы можете миновать Nginx и обратиться к сайту по другим портам. Если ваша панель управления хостингом:

  • ISPManager – используйте порт 8081
  • cPanel или Plesk – используйте порт 8080.

2 способ

Если этот вариант вам не подходит, рекомендуем перенести ваш сайт на Облачный сервер, на котором доступна гибкая настройка сервера, в том числе и лимитов. Для этого закажите услугу «Облачные серверы» и перенесите сайт по инструкции Как перенести сайты между услугами REG.RU.

3 способ

Также вы можете изменить директиву max_execution_time в файле php.ini. Она указывает на время, за которое должен отрабатываться скрипт. Для этого:

  1. 1.

  2. 2.

    Укажите нужное значение в строке:

    Где 30 – время выполнения скрипта в секундах.

4 способ

Если вы используете CDN, проблема может быть связана с ней.


Что такое CDN

CDN – это сетевая инфраструктура, которая распределена географически. Она обеспечивает быструю загрузку контента пользователям веб-сервисов и сайтов. Серверы, которые входят в состав CDN, географически расположены так, чтобы сделать время ответа сайта или сервиса минимальным для пользователей.
Пользователь ищет ресурс и тем самым посылает запрос. Запрос идентифицируется и направляется на PoP – на ближайший к пользователю кэширующий сервер в этой инфраструктуре. Возможны два варианта:

  • Если в кэше PoP есть данные об этом запросе, он отвечает браузеру, а тот отображает контент.
  • Если в кэше этого сервера нет данных, запрос переадресовывается к ориджину – центральному серверу, на котором хранятся все данные. Когда ориджин отвечает на запрос, PoP кэширует его и передаёт ответ браузеру. После этого контент отображается в браузере.

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

Если ошибку исправить не удалось, обратитесь в техническую поддержку.

Как исправить ошибку 504 на VPS

1 способ

Эта ошибка может возникнуть в случае, если для Nginx был превышен лимит на время ответа сайта. По умолчанию это 30 секунд, при этом среднее время загрузки сайта не должно превышать 1-3 секунды.
Чтобы избавиться от этой ошибки, попробуйте повысить время ожидания веб-сервера Nginx.

2 способ

Также ошибка 504 может возникать, когда Nginx используется как прокси-сервер для Apache. В этом случае нужно настроить параметры времени ожидания при проксировании. Максимальное время исполнения скрипта в настройках веб-сервера — 300 секунд.
Изменить параметры ожидания можно в конфигурационном файле nginx.conf. Для этого:

  1. 1.

    Подключитесь к серверу по SSH.

  2. 2.

    Откройте конфигурационный файл с помощью команды:

    sudo nano /etc/nginx/nginx.conf
  3. 3.

    Добавьте строки в блоке server:

    #server {
    
    #...
    
    proxy_connect_timeout 600;
    proxy_send_timeout 600;
    proxy_read_timeout 600;
    send_timeout 600;
    
    #...
    #}

    Где 600 — время в секундах.

  4. 4.

    Перезапустите Nginx с помощью команды:

Если решить проблему не удалось, обратитесь в техническую поддержку или на тематические форумы по Nginx.

Понравилась статья? Поделить с друзьями:
  • Error verifying data in ram
  • Error verify fail перевод
  • Error vent 1 must be attached to a solid obstruction mpi process 0 chid 1
  • Error vector magnitude что это
  • Error vector does not name a type