Request failed with status code 504

Request failed with status code 504

Ошибка 504 Gateway Time Out

Любой код ошибки, который начинается на цифру 5, говорит о том, что проблема возникла на стороне сервера. В этой статье мы рассмотрим ошибку 504 Gateway Time Out: откуда она появляется и как её исправить.

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

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

Также вы можете встретить другие варианты отображения ошибки:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

Как устранить код ошибки 504 Gateway Time Out владельцу сайта

Самые частые причины этой ошибки:

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

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

Конечно, лучше всего облегчить тяжёлый скрипт. Так он не будет нагружать сервер и вызывать ошибку. Однако не всегда есть возможность заменить его. В таком случае можно увеличить время ожидания сервера, чтобы весь скрипт успевал обрабатываться. По умолчанию максимальное время выполнения скрипта ― 30 секунд. Увеличить это время можно через PHP, настройки Nginx и Apache.

Изменить время обработки запроса можно в директиве max_execution_time в файле php.ini. Чтобы изменить это время:

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

Nginx

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

1. Перейдите в файл nginx.conf. Для этого введите команду:

2. Введите строки:

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

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

Обратите внимание! Если вы меняете время обработки запроса в Nginx, рекомендуем увеличить и max_execution_time в php.ini. В параметрах укажите то же количество секунд, что и указали в nginx.conf.

Apache

Если вы используете Apache, увеличить время обработки запроса можно в файле httpd.conf. Для этого:

1. Перейдите в файл httpd.conf.
2. Введите:

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

3. Сохраните изменения и перезапустите Apache.

Проблемы с CDN

CDN ― это множество связанных серверов, которые ускоряют передачу данных (фото, видео, скриптов) пользователю. CDN-серверы размещают как можно ближе к аудитории.

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

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

Также вместе с CDN часто используют прокси-сервер Cloudflare или Sucuri. Ошибка может появиться из-за них. Для её решения нужно обратиться в техподдержку сервиса.

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

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

Проблемы с сайтами на WordPress

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

Что может сделать пользователь

6. Обратитесь к интернет-провайдеру. Если проблема наблюдается на всех устройствах и браузерах, подключённых к общей сети, проблема может быть на стороне интернет-провайдера. Обратитесь в техническую поддержку компании, которая предоставляет вам услуги интернета.

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

504 Gateway Timeout Error

Here’s how to fix a 504 Gateway Timeout error

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

In This Article

Jump to a Section

The 504 Gateway Timeout error is an HTTP status code that means that one server didn’t receive a timely response from another server that it was accessing while attempting to load the web page or fill another request by the browser.

In other words, 504 errors usually indicate that a different computer, one that the website you’re getting the message on doesn’t control but relies on, isn’t communicating with it quickly enough.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Lifewire / Ashley Nicole DeLeon

Are You the Web Manager? See the Fixing 504 Errors on Your Own Site section further down the page for some things to consider on your end.

How You Might See the 504 Error

Individual websites are allowed to customize how they show «gateway timeout» errors, but here are the most common ways you’ll see one spelled out:

A 504 Gateway Timeout error shows up inside the internet browser window, just like normal web pages do. There might be a site’s familiar headers and footers and a nice, English message on the page, or it could show up on an all-white page with a big 504 at the top. It’s all the same message, regardless of how the website happens to show it.

Causes of 504 Gateway Timeout Errors

Most of the time, a 504 Gateway Timeout error means that whatever other server is taking so long that it’s «timing out,» is probably down or not working properly.

Since this error is usually a network error between servers on the internet or an issue with an actual server, the problem probably is not with your computer, device, or internet connection.

That said, there are a few things you can try, just in case:

How to Fix the 504 Gateway Timeout Error

Retry the web page by selecting the refresh/reload button, pressing F5, or trying the URL from the address bar again.

Even though the 504 Gateway Timeout error is reporting an error outside of your control, it might only be temporary.

Restart all of your network devices. Temporary problems with your modem, router, switches, or other networking hardware could be causing the 504 Gateway Timeout issue you’re seeing. Just restarting these devices could help.

While the order you turn off these devices isn’t important, the order that you turn them back on is. In general, you want to turn devices on from the outside-in. If you’re not sure what that means, check out the link at the beginning of this step for a complete tutorial.

Check the proxy server settings in your browser or application and make sure they’re correct. Incorrect proxy settings can cause 504 errors.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Most computers don’t have proxy settings at all, so if yours are empty, just skip this step.

See Proxy.org for an updated, respected list of proxy servers that you can choose from.

Change your DNS servers, especially if all the devices on your network are getting the same error. It’s possible that the 504 Gateway Timeout error you’re seeing is caused by an issue with the DNS servers you happen to be using.

Unless you’ve previously changed them, the DNS servers you have configured right now are probably the ones automatically assigned by your ISP. Others are also available to choose from. See our Free & Public DNS Servers list for options.

If nothing has worked up to this point, contacting the website is probably the next best thing to do. There’s a good chance the website administrators are already working to fix the root cause of the 504 Gateway Timeout error, assuming they’re aware of it, but there’s nothing wrong touching base with them.

Most major sites have social networking accounts they use to help support their services and some even have telephone numbers and email addresses.

If it’s starting to look like the website might be giving a 504 error for everyone, searching Twitter for real-time information about the site’s outage is often helpful. The best way to do this is to search for #websitedown on Twitter. For example, if Facebook might be down, search #facebookdown.

Contact your internet service provider. It’s very likely at this point, after following all the troubleshooting above, that the 504 Gateway Timeout that you’re seeing is a problem caused by a network issue that your ISP is responsible for.

Come back later. You’ve exhausted all your options at this point and the 504 Gateway Timeout error is either in the hands of the website or your ISP to correct. Check back with the site regularly. No doubt it’ll start working again soon.

Fixing 504 Errors on Your Own Site

A lot of times this isn’t your fault at all, but it’s not the user’s either. Start by checking that your server can properly resolve all the domains that your applications require access to.

Very heavy traffic might result in your server serving a 504 error, even though a 503 would probably be a bit more accurate.

In WordPress specifically, 504: Gateway Timeout messages are sometimes due to corrupted databases. Install WP-DBManager and then try the «Repair DB» feature, followed by «Optimize DB,» and see if that helps.

Also, make sure your HTACCESS file is correct, especially if you have just reinstalled WordPress.

Finally, consider contacting your hosting company. It’s possible that the 504 error that your website is returning is due to an issue on their end that they’ll need to resolve.

More Ways You Might See a 504 Error

A Gateway Timeout error, when received in Windows Update, generates a 0x80244023 error code or the message WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT.

In Windows-based programs that inherently access the internet, a 504 error might show up in a small dialog box or window with the HTTP_STATUS_GATEWAY_TIMEOUT error and/or with a The request was timed out waiting for a gateway message.

A less common 504 error is Gateway Time-out: The proxy server did not receive a timely response from the upstream server, but the troubleshooting (above) remains the same.

Errors Like 504 Gateway Timeout

A number of error messages are similar to the 504 Gateway Timeout error because they all occur on the server side. A few include the 500 Internal Server Error, the 502 Bad Gateway error, and the 503 Service Unavailable error, among a few others.

There are also HTTP status codes that aren’t server-side, but instead client-side, like the commonly seen 404 Not Found error. Several others exist as well, all of which you can see in our HTTP Status Code Errors page.

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

При заходе на сайт выдается ошибка 504 Gateway Timeout Error. Как ее исправить?

Ответ

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Существует несколько способов для решения проблемы.

Способ 1. Перезагрузка страницы в веб-браузере

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Способ 2. Отключение параметров прокси

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

Способ 3. Проверка службы DNS

Ошибка 504 Gateway Timeout Error также может быть вызвана проблемами с DNS-службой, а именно на сервере, когда, например, домен не преобразован в корректный IP. Часто такое случается, если Вы только что перенесли свой сайт с локального компьютера на хостинг. В таком случае необходимо дождаться распространения DNS-данных по всей Сети (обычно до 48 часов).

Наконец, Вы вправе на какое-то время изменить DNS-сервера Вашего хостинга на публичные (например, 8.8.8.8 или 8.8.4.4 от Google).

Способ 4. Временное отключение CDN

Иногда ошибка 504 может появляться вследствие использования прокси-серверов типа Cloudflare или Sucuri. Например, для первого сервиса существует два типа ошибки 504.

Вариант 1

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

В этом случае проблема действительно со службой Cloudflare. Для ее решения нужно обратится в техподдержку сервиса.

Вариант 2

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Способ 5. Проверка хостинга

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

Способ 6. Проверка и выявление спама, вирусов и DDoS-атак

Еще одна причина возникновения ошибки 504 – это наличие спама, вируса или DDoS-атаки, что может привести к перегрузке и отказу сервера. В таком случае необходимо, во-первых, ознакомится с предоставляемыми компанией-хостингом инструментами для борьбы с вышеперечисленными угрозами. Часто в админ-панели хостинга присутствуют антивирус, а также включение защиты от DDoS-атак. Что касается спам-комментариев на сайте WordPress, то с этим довольно эффективно борются соответствующие плагины (например, самый популярный среди пользователей Akismet Anti-Spam ). Для выявления угроз обычно изучают статистику сервера, статистику поисковых систем на предмет подозрительных IP-адресов.

Способ 7. Проверка активных тем и плагинов

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

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

504 Gateway Timeout Error and How to Fix It

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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:

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Different platforms can change the timeout error message. So you can come across different timeout messages but they all have the same meaning.

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:

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

There’s no message after processing this command, you can add your own, by running the command in this way

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:

For a dnsmasq DNS cache:

For a BIND DNS cache:

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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:

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

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.

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

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

To increase the time limit for all sites, open the /etc/nginx/nginx.conf file and

After changing params don’t forget to reload PHP FPM and Nginx:

If you’re using Nginx as a reverse proxy server for Apache then you have to change these directives in your nginx.conf file:

After increasing params reload Nginx

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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.

See How 10Web Can Benefit You

Visit our homepage to learn more about the first-ever AI-powered WordPress platform.

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Ошибка 504 что значит

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

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Что такое тайм аут шлюза

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

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

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

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

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

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

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

How to Fix the 504 Gateway Timeout Error on Your WordPress Site

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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?

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.

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504The ‘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).

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504The ‘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:

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504GitHub’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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Viewing 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 WordPress 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.

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Refreshing 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?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Testing Kinsta.com on Down for Everyone or Just Me

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.

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Changing 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.

DNS Issues

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Checking 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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Flushing 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Settings custom DNS servers in Windows 10

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Setting 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Disable 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Cloudflare’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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Error 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Check 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Cloudflare’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.

Server Issues (Check With Your Host)

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

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

Sign Up For the Newsletter

Want to know how we increased our traffic over 1000%?

Join 20,000+ others who get our weekly newsletter with insider WordPress tips!

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504A 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 WordPress 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 WordPress hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your WordPress 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Monitor 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504WebGazer 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 managed WordPress hosts 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.

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504MyKinsta 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Viewing ‘Top Client IPs’ in MyKinsta dashboard

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

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

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

Finally, you can use a WordPress 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 WordPress 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 WordPress site and how Sucuri helped stop a DDoS attack in its tracks.

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.

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Deactivating 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.

Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your WordPress 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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Checking 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.”

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Accessing 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:

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

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

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:

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 WordPress 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 WordPress site, leave a comment below.

Save time, costs and maximize site performance with:

All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.

Ошибка 504 — что это значит и как исправить

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

HTTP Status 504

I’m getting the following error when my win32 (c#) app is calling web services.

I understand ‘I think’ that this is because the upstream request does not get a response in a timely fashion.

But my question is this? How do I change the app.config settings in my win32 application to allow more time to process its data. I assume I require these changes to be made on my app settings as the webservices and IIS hosting the ws are setup with extended times.

Look forward to a response and thank you in advance.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can’t. The problem is not that your app is impatient and timing out; the problem is that an intermediate proxy is impatient and timing out. «The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI.» (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) It most likely indicates that the origin server is having some sort of issue, so it’s not responding quickly to the forwarded request.

Possible solutions, none of which are likely to make you happy:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).

If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.

for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You’d better improve the design to really solve this problem.

If your using ASP.Net 5 (now known as ASP.Net Core v1) ensure in your project.json «commands» section for each site you are hosting that the Kestrel proxy listening port differs between sites, otherwise one site will work but the other will return a 504 gateway timeout.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.

I have had another issue giving me a 504. It’s pretty far out but I’ll write it up here for googlers and posterity.

I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.

In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)

This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.

After removing the spn and allowing the call to fall back to NTLM, it works fine.

504 Ошибка таймаута шлюза

Вот как можно исправить ошибку 504 Gateway Timeout

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

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

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

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

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

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

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

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

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

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

Тем не менее, есть несколько вещей, которые вы можете попробовать, на всякий случай:

Как исправить ошибку времени ожидания шлюза 504

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Очень большой трафик может привести к тому, что ваш сервер выдаст ошибку 504, хотя 503, вероятно, будет немного более точным.

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

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

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

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

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

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

Что значит ошибка «504 Gateway Time-out» и как решить проблему

Ошибка под номером 504 наиболее распространена среди сайтов на просторах интернета. В подавляющем большинстве случаев пользователи видят надпись «504 Gateway Time-out (time out)» на белом фоне и уходят с сайта, не разбираясь в причинах потери работоспособности ресурса. Куда более неприятно видеть код 504 владельцам сайта, особенно если неизвестно какими причинами была вызвана ошибка и что нужно делать, чтобы её исправить.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Что означает ошибка «504 Gateway Time-out»

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

Техническая сторона вопроса

В подавляющем большинстве случаев проблема с кодом 504 возникает:

Такое сочетание чаще всего генерирует ошибку 504 с примечанием Gateway Time-out. В такой связке nginx выступает в качестве чего-то вроде распределителя запросов пользователя, и они сначала попадают к нему, а не напрямую в Apache. И если из-за высокой нагрузки сервер Apache не смог вовремя ответить, nginx пошлёт пользователю соответствующий ответ в виде кода 504.

Из-за чего появляется ошибка 504

Появление ошибки 504 характерно для серверов Apache в случае большой нагрузки. Такие сервера имеют особенность: при поступлении большого количества запросов они не успевают обрабатываться. Всем пользователям, у которых браузеры не получили HTTP-ответ от сервера, будет показана ошибка 504 Gateway Time-out.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Ошибка на стороне скриптов

Иногда код «504 Gateway Tme-out» вызывает не чрезмерная нагрузка, а неправильная настройка скриптов на сайте. Любому скрипту отводится определённый отрезок времени на выполнение. На практике, по ряду причин, этого времени скрипту может не хватить.

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

Задержка в процессе выполнения скриптов на сайте может вызываться и другими причинами:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

В том случае, если сайт с достаточно высокой посещаемостью (или требующий много ресурсов) располагается на обычном виртуальном хостинге, мощностей может элементарно не хватать. Некоторые хостеры присылают своим клиентам уведомления о превышении допустимой нагрузки, некоторые – нет. Следует посмотреть логи и запросить нужную информацию о технической поддержке хостинга. Вполне возможно, что с сайтом всё в порядке, просто из-за роста посещаемости пора переходить на VPS, VDS и другие тарифы и услуги с существенно большими ресурсами.

Видео

Из видео вы узнаете, как самостоятельно исправить ошибку «504 Gateway Time-out (time out)».

How to Fix the HTTP 504 Gateway Timeout Error Code?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

There is nothing more annoying than a blank screen with an error message instead of your website’s content. Today, we’ll take a look at the 504 Gateway Timeout Error, and also give some recommendations on how to fix it on your WordPress site. For most blogs and online stores, such errors can lead to a loss of revenue. The visitors immediately leave the resource with a bad experience, and cannot make purchases. So let’s dive in –

What is the 504 Gateway Timeout Error?

HTTP status codes starting with 5 are server-side errors. They appear when the request cannot be performed due to a connection failure between several servers.

What does 504 gateway timeout mean? 504 Gateway timeout error is an HTTP status code. It appears when one server does not receive a timely response from another one that works as a gateway or proxy. Simply put, 504 gateway timeout means that the server could not complete your request within some period.

There are many error messages that you might see. Some common errors that you might have encountered:

As there are a variety of web browsers, operating systems, and types of servers, they display the 504 error in many ways. All of them, as a rule, mean the same. We listed some of the most popular versions of HTTP error 504:

What Are The Causes for 504 Gateway Timeout Error?

Before we consider the error itself, it is important to understand why it appears. Whenever you start your browser and visit a URL, it sends the request back to the server where it is hosted. The web server then processes the request and sends you the requested resources along with an HTTP header. This header contains one of the many HTTP status codes that let you understand whether everything is okay or something went wrong. Not all status codes are bad. For example, the status code 200 indicates that everything works fine.

Any status code in the 500-s is an error code (500, 501, 502, 503, 504, etc.) that has different meanings. They indicate that the request was accepted, but the server could not execute it.

To that extent, the HTTP 504 error means that the server running as a gateway is out of time to wait for a server response. The code is returned when there are two servers involved in processing the request, and the response time from the second server has expired.

In addition to server timeouts, there are other causes, leading to the 504 error code:

We hope that you like our content. We are sure you will love our plans starting at just $16.61 we give free SSD storage, SSL, Premium themes and plugins, WP Dev & Server Support, Daily Malware Scanning & Cleanup, and Business Emails, Host unlimited Sites with every plan.

How to fix the HTTP 504 gateway timeout error?

When you see a 504 Gateway timeout error, you might be confused about what to do? You can always try the following actions –

Try to reload the page:

One of the first things you should do when you face the HTTP Error 504 Gateway Timeout is just to wait a minute and reload the page. Perhaps the hosting or server is simply overloaded, and the site will quickly return to work.

Another thing you can do is check your website status on downforeveryoneorjustme.com. This site will tell you if the site is out of service only for you or for all visitors. The tool checks the HTTP status code that is returned by the server. If the code differs from 200, then, in this case, you will see the Down pointer. It will mean that the site does not work for everyone.

Try a different browser:

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

Check on different devices:

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

Disable the proxy:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Sometimes you may get an HTTP 504 error if you use a proxy server. These cases are very rare, especially on the client side. Read the guides on how to disable proxy on Windows and Mac.

Check DNS records propagation:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

HTTP Error 504 gateway timeout is often caused by problems with the DNS server. There are two reasons for that. On the server side, it happens when the domain name is not changed to the correct IP address. If you just moved the WordPress website to a new hosting, it’s important to wait until the address will be added to the DNS base. In most cases, it takes up to 24 hours. It all depends on your DNS records TTL value. You can use a free tool like DNSMap to check if your DNS has spread all over the world.

The second DNS issue relates to the client-side. In this case, you can clear your local DNS cache. This is similar to clearing the browser cache.

In Windows, simply open a command line and type the following:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

In macOS, type the following in the terminal:

Note: there are no messages of successful operations on Mac.

And, finally, you can temporarily change your client’s DNS servers. By default, DNS servers are provided by your ISP. You can temporarily change them to a public DNS server, for example, provided by Google. Some people prefer to use Google’s public DNS constantly because in some cases they are more reliable.

Temporarily disable the CDN:

Also, the problem may relate to the content delivery network. If you use a third-party CDN provider, you can try to temporarily disable it. For that, you may use WordPress plugins. With them, you will be able to disable the CDN safer.

If you use the back proxy services like Cloudflare or Sucuri, they may cause the 504 gateway timeout error as they use the additional firewall. Most of the cache 500 state codes when they are returned by your source server. Many users noticed that issue on Cloudflare’s free plan. Unfortunately, since Cloudflare is a complete proxy service, there is no quick way to disconnect it.

However, before blaming Cloudflare, it is important to know that there are two types of 504 gateway timeout errors:

504 Gateway Timeout in Cloudflare (version 1)

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If you see the page looking like that, then, in this case, the problem is on the Cloudflare side. Contact their user support. Or check their status page. Most likely, they are already notified about this problem and are working on it.

504 Gateway Timeout in Cloudflare (version 2)

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If you see the page looking like that, then this is a problem with your WordPress hosting. Please follow the recommendations from the next section.

Check the issues with your hosting provider:

Server problems are one of the common reasons why users experience 504 errors on their WordPress websites. In simple terms, Nginx or Apache waits for a response until the waiting time has expired.

504 errors are very popular on sites with a lot of visitors and e-commerce sites and online stores. The latter may have installed e-commerce plugins like Woocommerce. They usually have many non-cached requests. This can cause the server to overload. However, such errors can happen to a variety of website types, including blogs. Many hosters usually offer to upgrade to a more expensive tariff plan to fix this problem. And even if this usually helps to solve this issue, it is often not necessary.

Some hosting provides dedicated resources for each server. This means that each site is hosted in its isolated container. It has all the necessary software resources required to run it (Linux, Nginx, PHP, MySQL). Resources are 100% confidential and do not share with anyone. But some shared WordPress hosting plans do not have this feature. So any neighboring site with high traffic will cause an error 504 gateway timeout on your site.

It is also important to note that HTTP 504 errors may look very similar to 503 errors (service unavailable) or even 502 errors (bad gateway). But actually, they are different.

If you want to prevent such errors in the future, you can use a tool like statuscake.com to track the server state and immediately report any problems. The service periodically sends an HTTP HEAD request to the specified URL. You can simply set your homepage. In addition, you can choose the checking frequency from 15 seconds to 10 minutes.

The service will send you an email if your site is out of service, indicating the time when it happened.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

This can be especially useful if you are using virtual hosting, which, as a rule, is constantly overloaded. This will give you proof that your site did not work (for example, at night). For this reason, we advise you to move on to dedicated hosting.

Clean the site from spam, bots and protect it from DDoS attacks:

Perhaps your website has been spammed by bots or become a DDoS attack target. Sometimes this leads to uncached requests and, as a result, to server overload. All that results in an HTTP error 504 gateway timeout. You can learn the server analytics to see if there are any patterns in it. You can request your hosting provider for this information.

The first report, which we recommend studying, is the top-end customer’s IP addresses. Usually, this is very useful, especially if your site suddenly began to generate large traffic or was attacked by bots.

The second report we recommend looking at is the requests and bots. You can quickly compare the number of people visiting your website, with the number of bots. However, remember that not all bots are bad. Google Bot is a good bot, it scans the site to index the content and promote it in the search engine.

The third report we recommend is a cache analysis. Here you can see what requests are missing in the cache, and also what are the top locations of your site. To provide the best performance and stability, you should try to cache as many requests as possible. This is not always available because some resources generate a huge amount of uncached requests. The best example is Woocommerce. These requests are necessary for the correct work and synchronization.

If on your site you find and identify traffic or IP addresses that need to be blocked, you can use the WordPress security plugin. However, not all hostings allow you to install security plugins. First, such plugins can influence performance, especially when they scan the server. Second, the IP blocking feature may not work in them because the hosting provider can use load balancers from the Google Cloud Platform.

Naturally, IP addresses can always be blocked by the hosting support service. However, depending on how long and large is an attack, this can never end. When the attacks or spam is blocked in one area, they are often switched to other zones, changing IP addresses or using other proxies. Therefore, in this case, we recommend installing a security solution, such as Cloudflare or Sucuri.

Check your plugins and themes:

Many users believe that third-party plugins or themes do not lead to 504 gateway timeout errors. And in most cases this is true. But, according to many users’ experience, a slow non-cached plugin request can cause delays, since it uses more of your PHP workers. Once you reach the limit of them, the queue will remove your old requests, which can cause the HTTP 504 errors. They should not be confused with 502 errors which are the result of a 60 seconds timeout.

There are several ways to fix the issue. One of them is the deactivation of all your plugins. Remember that you will not lose your data if you disable them. If you have access to the admin panel, simply go to the Plugins section and select Deactivate feature. This will disable all of your plugins.

If this fixes the issue, you need to find its source. Activate the plugins one by one, restarting the site after each activation. Once you see the HTTP 504 error, you will be able to identify the problematic plugin. Then you can contact the plugin developer for help or create a ticket in the WordPress repository.

If you do not have access to the admin panel, you can use the FTP client to connect to your server. Rename the plugin folder to something like plugins_old. Then check your site again. If this works, you will need to test each plugin separately to find the reason. Rename the plugins folder back. Then rename the plugin folders inside until you find the plugin causing the issue.

Make sure that all your plugins, themes, and the WordPress kernel are updated to the latest version. And make sure that you are using a supported version of PHP.

If the plugin contains bad code, then you will most likely need to contact the WordPress developers to solve this problem.

Ошибка 504: что это, почему возникает и как ее исправить

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

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

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

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

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

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

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

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Очистка DNS

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

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

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

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

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

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

The Quick & Easy Guide to Fixing 504 Gateway Timeout Errors

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If you’ve ever visited a website that served you an error page, you know how frustrating it is.

One of the worst things you can do as a brand is not meet your audience’s needs and expectations. If your website visitors see an error page when they’re looking for help or information, they could get frustrated and lose trust in your brand, permanently damaging your reputation.

The 504 Gateway Timeout Error is one type of error that can hurt the user experience in this way. To help you avoid losing brand sentiment and consumer trust, we’ve fleshed out exactly what this error means and what its most common causes and solutions are.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

What is a 504 Gateway Timeout Error?

A 504 Gateway Timeout Error means your web server didn’t receive a timely response from another server upstream when it attempted to load one of your web pages. Put simply, your web servers aren’t communicating with each other fast enough. Since a 504 Gateway Timeout Error is rather generic, it doesn’t actually pinpoint the exact cause of the issue. When this happens, your website will serve an error web page to your site’s visitors.

Here’s how a 504 Gateway Timeout Error might appear in your user’s browser:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504Image Source

504 Errors Wording

The screenshot above depicts how a 504 Gateway Timeout Error appears in one server. Below are some other common ways a 504 error might appear, depending on the server, operating system, or browser you’re using.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

So now we know how the 504 error is worded — but what does it mean exactly? Let’s decode it below.

What does 504 gateway timeout mean?

When visiting a website, your server sends a request to another server where that site is hosted. This server — known as the «upstream server» — receives the request and responds with whatever resources are needed to load the website on your browser.

However, a 504 Gateway Timeout error means that your server didn’t receive a quick enough response from the upstream server. Because its request timed out, your server is unable to load the web page and, ultimately, fulfill its role as a gateway — hence the name «Gateway Timeout» error.

You might be wondering what exactly causes the delay in the upstream server’s response — and that’s a good question. Let’s address it below.

504 Gateway Timeout Causes

504 Gateway Timeout Errors are among the most frustrating HTTP status codes you can receive. They indicate what happened to your website, but they don’t tell you why it happened, making it challenging for you to pinpoint its cause and ultimately correct the issue.

Below are a few possibilities.

Server Connectivity Issues

Most websites live on multiple servers or third-party hosting providers. If your server is down for maintenance or any other reason, your website could serve visitors a 504 Gateway Timeout Error page.

DNS Changes

If you’ve recently changed servers or moved your website to a different IP address, it’ll make changes to your website’s DNS server. This could cause your website to serve its visitors a 504 Gateway Timeout Error page. Your website won’t be up and running until these DNS changes take full effect, which can take a few hours.

Faulty Firewall Configurations

Your firewall is your website’s gatekeeper, protecting your site from malicious visitors or distributed denial-of-service (DDoS) attacks. Sometimes, a faulty firewall configuration will cause your firewall to deem requests from a content delivery network as an attack on your server and reject them, resulting in a 504 Gateway Timeout Error.

Errors in Your Website’s Code

If there’s a mistake in your website’s code, your server might not be able to correctly answer requests from a content delivery network.

Network Connectivity Errors

Since a 504 error is the result of a timeout during the processing of a request between servers, the problem likely lies with them — not the user’s internet connection or device. However, if only one user reports seeing a 504 error on your site, it could have to do with their modem, router, or another device. or their internet connection.

Since there are multiple reasons why a 504 error might occur, it will ultimately be up to you to rule each one out until you find the true cause. Fortunately, there are five common and effective solutions for fixing most 504 Gateway Timeout Errors’ causes.

How to Fix 504 Gateway Timeout Errors

1. Look for server connectivity issues.

If your server is down for maintenance or any other reason, then your website will likely serve visitors a 504 Gateway Timeout Error page. The only way to troubleshoot this issue is to wait for your server to finish maintenance or fix the problem causing the error.

2. Check for any DNS changes.

If you’ve recently changed hosting providers or moved your website to a different IP address, then your website’s DNS server will need to be updated. These DNS changes take a few hours to process so in the meantime your website might serve visitors a 504 Gateway Timeout Error page. The only solution is to sit tight while these DNS changes take effect.

3. Sift through your logs.

If the problem is not your server’s connection or DNS information, then check out your server logs. These logs provide details about your server’s health and status. Sifting through them may uncover other issues that could be causing a 504 error.

4. Fix faulty firewall configurations.

A faulty firewall configuration may be the reason behind your 504 Gateway Timeout Error. To rule it out as the cause, you can temporarily deactivate your firewall.

If your device runs on Mac OS, then simply navigate to System Preferences > Security & Privacy > Firewall to deactivate it.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Once you’ve deactivated your firewall, check to see if the 504 error is resolved. If it is, you can either reconfigure the settings of your existing antivirus program or switch to a new one.

If the error is not resolved, don’t forget to reactivate your firewall before moving onto the next step.

5. Comb through your website’s code to find bugs.

Comb through your code to find any bugs or copy your code into a development machine. It’ll perform a thorough debug process that will simulate the situation in which your 504 Gateway Timeout Error occurred and allow you to see the exact moment where things went wrong.

6. Contact your hosting provider.

Contacting your hosting provider should be a last resort. But if you’ve tried the steps above and are still seeing the 504 Gateway Timeout error, they may be able to solve the issue or provide valuable insight.

How 504 Gateway Timeout Errors Affect SEO

Fixing a 504 Gateway Timeout Error can take time — but it’s well worth the effort considering how it can impact your site’s technical SEO.

Like an HTTP 500 Internal Server Error, 503 error, or any other 5xx error, a 504 Gateway Timeout error prevents your website from loading. This not only hurts the user experience — it also hurts your SEO performance.

If a web crawler attempts to crawl one of your pages and is served a 504 error, then it can’t crawl the page. If that page has already been indexed, then it might be lowered in the search engine results. Or it might be deindexed if the error persists.

Resolving the 504 Gateway Timeout Error

There’s no foolproof way to prevent 504 Gateway Timeout Errors on your site, but there are steps you can take to resolve them. By fixing this error as quickly as possible, you’ll ensure that visitors continue to have seamless experiences on your site and mitigate any negative impacts on your SEO.

Editor’s note: This post was originally published in January 2019 and has been updated for comprehensiveness.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Originally published Aug 12, 2021 1:00:00 PM, updated August 12 2021

Request failed with status code 504 from nginx

I’m still learning, so I apologize if I’m wrong. I am working on a project with React as the frontend and Java + Spring as the backend. The project is being tested and we are using Nginx as a reverse proxy.

I am experiencing this problem in an http call with axios.

In practice I make a call that goes to take about 60k data from the database and generates an excel (via Workbook) by entering all the data inside. This takes about 35 seconds. My problem is that at 30s I get out: request failed with status code 504, but the backend is continuing to run.

I added the timeout to the Axios call, it works, but that’s not the problem.

Reading on the internet, the problem seems to be the nginx timeout. Reading various guides, I read to add:

To the nginx.conf file. Since I don’t have this path locally. But I found it through OpenShift terminal, is there a way to add these lines to that file? Should I add them via terminal? Or is there some simpler way?

I tried adding these lines to my project config file, but it doesn’t work. Thanks to anyone who helps me and I apologize if I may have been unclear about some things or if I was wrong to write something.

What can I do to fix a 504 gateway timeout error?

I have been using jquery to try and pull data from an API. However I am getting a 504 error. Even when I am using postman to test the data this happens. Can anyone suggest what I need to do to get around this?

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

For those experiencing this error, that have access to their app / site’s hosting environment, which is proxying through NGINX, this issue can be fixed by extending the timeout for API requests.

In your /etc/nginx/sites-available/default or /etc/nginx/nginx.conf add the following variables:

This should effectively quadruple the time before NGINX will timeout your API requests (the default being 60 seconds, our new timeout being 240 seconds).

Hope this helps!

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

There is nothing you can do.

You are sending a request to a server. This particular request fails, because the server sends a request to a proxy, and gets a timeout error. Your server reports this back to you as status 504.

The only way to fix it is to fix the proxy (make it respond in a timely manner), or to change the server to not rely on that proxy. Both are outside your area.

You cannot prevent such errors. What you can do is find out what user experience there should be when such a problem happens, and implement it. BTW. If you get 504 errors, then you should also expect timeout errors. Say you make a request to your server with 60 second timeout, and your server makes a request to the proxy with 60 second timeout. Because both timeouts are the same, sometimes your server will receive the proxy timeout and send it to you (status 504), but sometimes your request to the server will time out just before that, and you get a timeout error.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как можно исправить ошибку 504 Gateway Timeout

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

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

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

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

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

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

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

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

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

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

Есть несколько вещей, которые вы можете попробовать, на всякий случай:

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

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

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

Очень большой трафик может привести к тому, что ваш сервер выдаст ошибку 504, хотя 503, вероятно, будет немного более точным.

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

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

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

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

Ошибка 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. Также существует несколько других, которые вы можете увидеть на нашей странице HTTP Ошибки кода состояния.

Ошибка 504 Gateway Time-out в браузере означает, что сервер не получил своевременного ответа от клиента (пользователя) и запрос не был обработан. Обычно это связано с перегруженностью сервера, который не успевает обрабатывать текущие HTTP запросы. Например, имеется слабый сервер на котором находится сайт, и если на сайт зайдет 20 000 пользователей, то сервер не успеет обработать все эти запросы и выдаст ошибку с кодом 504 Gateway Timeout и указанием на структуру сервера nginx или apache.

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

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

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

Как исправить 504 gateway time out Nginx

Веб-сервер Nginx часто работает не только в качестве самого веб-сервера для отдачи контента, но и в качестве прокси, когда он вступает только посредником. Такая ситуация наблюдается намного чаще, чем можно было бы ожидать. Например, при работе с php-fpm и другими модулями динамических языков.

Именно в таком режиме может наблюдаться ошибка 504 gateway time out Nginx. В нашей сегодняшней статье мы попытаемся разобраться почему она возникает и как с ней бороться. Разберем несколько способов решения и причин.

Что значит 504 gateway time out Nginx?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как я уже сказал, такая ошибка возникает, когда сервер Nginx работает в режиме прокси. Например, при использовании php-fpm или Apache. Дословно, она означает, что превышено время ожидания ответа от сервера. В нашем случае, превышено время ожидания ответа от php-fpm. Рассмотрим несколько причин такого поведения:

Дальше рассмотрим что можно сделать если вы встретились с ошибкой 504 gateway time out Nginx.

Как исправить 504 gateway time out Nginx?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Нагрузку на процессор можно узнать командой htop:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Здесь 300 означает 300 секунд, для большинства скриптов, этого будет вполне достаточно, но вы можете еще больше увеличить значение если это нужно. Также ошибка 504 может возникать, когда Nginx используется в качестве прокси для Apache или любого другого веб-сервера, тогда нужно еще настроить время ожидания для прокси. Добавьте эти строки в секцию server:

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

sudo systemctl restart nginx

Более подробную информацию иногда можно увидеть в error.log:

Дальше, если проблема именно в php-fpm, вы можете отследить какие скрипты выполняются медленно с помощью встроенной функции slow-log. Для ее активации добавьте следующие строки в конфигурацию вашего пула:

sudo vi /etc/php-fpm.d/www.conf

slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Выводы

В этой статье мы рассмотрели как исправить 504 gateway time out Nginx 1.2 7, а также почему может возникнуть эта ошибка. Надеюсь, эта информация была полезной для вас.

Ошибка 504 «Тайм-аут шлюза»: как решить эту проблему при просмотре веб-страниц

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

Что такое ошибка 504 «Тайм-аут шлюза»

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

Что касается кодов статуса HTTP, которые начинаются с цифры » 5 «, Мы можем рассматривать их как те ошибки, которые исходят со стороны сервера. Эти типы ошибок возникают каждый раз, когда невозможно выполнить запрос из-за ошибки связи между несколькими серверами. В 504 Ошибка «Тайм-аут шлюза» происходит, когда наш браузер пытается загрузить веб-сайт, но по какой-то причине этот удаленный сервер не возвращает ответ. Это был бы пример этой неудачи:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

Причины и все решения для исправления ошибки 504

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

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

Обновите веб-страницу, которую мы посещаем

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Мы также можем обновить веб-страницу, нажав клавишу F5 или повторно набрав URL-адрес и нажав клавишу ВВОД. Если с этим мы не сможем решить эту проблему, нам придется попробовать другой из следующих вариантов.

Перезагрузите устройства и попробуйте другой веб-браузер.

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

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

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

Изменить DNS-серверы

Игровой автомат DNS Серверы также могут быть причиной того, что домен не может быть правильно определен и возникает ошибка 504. Таким образом, мы могли бы рассмотреть возможность изменения DNS-серверов в Windows TCP / IP или в самом роутере. Как правило, если мы используем маршрутизатор от провайдера, он будет использовать свой собственный DNS, и может быть удобно их изменить. Это будет пример изменения TCP / IP версии 4 Windows:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Здесь, например, вместо DNS нашего интернет-провайдера мы использовали DNS-серверы Google. С другой стороны, VPN или соединение через анонимный прокси-сервер также может использоваться в случае, если мы не можем получить доступ к Интернету из-за геоблока или другой проблемы.

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Связаться с владельцем сайта

Как вы видели, хотя ошибка 504 возникает на стороне веб-сервера и со всеми промежуточными узлами, возможно, что путем внесения определенных изменений в наше оборудование мы сможем решить эту ошибку, особенно с изменением DNS, потому что это возможно, что не «отправить» на другой веб-сервер рассматриваемой страницы, и даже если мы используем VPN или прокси-сервер, мы также можем получить к нему доступ, если это приведет нас к другому серверу, чем тот, на который влияет.

Что означает тайм-аут 504 Gateway и как его исправить

Когда у вас возникают проблемы с доступом к определенным веб-сайтам, ваш браузер часто отображает Код состояния HTTP это поможет вам разобраться в проблеме. Эти коды бывают разных типов и вариаций, каждый из которых имеет свое индивидуальное значение и решения. С вероятностью 90% вы хотя бы раз столкнулись с ошибкой 504 Gateway Timeout во время серфинга в Интернете.

Что означает тайм-аут 504 Gateway Timeout? Ошибка 504 Gateway Timeout обозначается по-разному на разных веб-сайтах и ​​в браузерах, но эти варианты означают одно и то же. Таким образом, если определенный веб-сайт выдает ошибку «Тайм-аут шлюза (504)», в то время как другие отображают свою как «Ошибка HTTP 504», «Домен слишком долго отвечает» или «Тайм-аут шлюза», они указывают на ту же проблему.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Что означает ошибка тайм-аута шлюза 504?

Многое происходит за кулисами, когда вы посещаете веб-сайт или щелкаете ссылку в браузере. Обычно это выполняется следующим образом:

Если ваш браузер отображает ошибку 504 Gateway Timeout вместо функциональной веб-страницы, это означает, что на шаге 4 возникла проблема. То есть серверы веб-сайта не смогли обработать запрос вашего браузера достаточно быстро.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Что вызывает ошибку тайм-аута шлюза 504?

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

Сбои на стороне сервера обычно являются причиной ошибки 504 Gateway Timeout, поэтому администратор веб-сайта находится в лучшем положении, чтобы решить проблему. Тем не менее, вам также следует устранить неполадки на вашем устройстве. Это связано с тем, что ошибка тайм-аута 504 также может возникать из-за проблем с вашим устройством или настройками сети, хотя такая возможность встречается довольно редко.

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

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

1. Обновите веб-страницу.

Как упоминалось ранее, веб-сайт может отображать код ошибки 504, если его серверы перегружены — возможно, из-за внезапного всплеска трафика. Если это причина ошибки, перезагрузка веб-страницы может вернуть все в нормальное состояние. Щелкните значок круглой стрелки рядом с адресной строкой или нажмите F5, чтобы перезагрузить страницу.

Вы также можете перезагрузить страницу в любом браузере с помощью сочетания клавиш Control + R (для Windows) или Command + R (для Mac).

2. Перезагрузите маршрутизатор или сетевое устройство.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

3. Проверьте настройки прокси.

Если вы используете прокси на своем компьютере, убедитесь, что настройки сервера верны и правильно настроены. Выберите «Настройки»> «Сеть и Интернет»> «Прокси-сервер» (для Windows) или «Системные настройки»> «Сеть»> «Дополнительно»> «Прокси» (для macOS), чтобы проверить наличие ручной настройки прокси-сервера.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

4. Измените DNS-серверы.

Большинство компьютеров используют серверы доменных имен (DNS) по умолчанию, назначенные поставщиком услуг Интернета (ISP). Эти серверы, назначенные интернет-провайдером, иногда бывают ненадежными и вызывают такие проблемы, как медленное соединение. Если уязвимая веб-страница успешно загружается на другом устройстве, измените поставщика DNS вашего ПК на любой бесплатный и надежный публичный сервер с быстрым временем отклика. Это может иметь большое значение.

Изменить DNS в Windows

Чтобы изменить поставщика DNS в Windows, перейдите в «Настройки»> «Сеть и Интернет»> «Статус» и нажмите «Изменить параметры адаптера».

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Изменить DNS в macOS

Для пользователей Mac перейдите в Системные настройки> Сеть и нажмите кнопку «Дополнительно» в нижнем левом углу.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Перейдите на вкладку DNS и щелкните значок плюса (+) в левом углу кнопки, чтобы добавить новый DNS-сервер.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Добавьте эти Google Public DNS: 8.8.8.8 и 8.8.4.4. Нажмите ОК, чтобы продолжить, и нажмите Применить на следующей странице, чтобы сохранить изменения.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

5. Очистите кеш DNS.

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

Ошибка тайм-аута может возникнуть, если веб-сайт изменит свой IP-адрес или сервер. Это связано с тем, что кеш DNS направит ваш браузер на старый (или устаревший) IP-адрес. Вы можете решить эту проблему, очистив кеш DNS. Это побудит ваше устройство и браузер получить обновленную информацию DNS при следующем посещении веб-сайта.

Чтобы очистить кеш DNS на Mac, запустите Терминал (перейдите в Приложения> Утилиты> Терминал), вставьте команду ниже в консоль и нажмите Return.

При появлении запроса введите пароль вашего Mac и нажмите Return.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Для устройств Windows запустите командную строку (нажмите Windows + X и выберите Командная строка (администратор)), вставьте команду ниже в консоль и нажмите Enter.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Наслаждайтесь безошибочным Интернетом

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

Что значит ошибка 504 Gateway Time-out

Содержание статьи

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Что значит ошибка 504 Gateway Timeout (time out)?

Как устранить ошибку 504 Gateway Timeout (time out)?

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

Справиться с насущной проблемой может только администратор сервера, который должен увеличить его производительность в несколько раз. Осуществить задуманное можно только если увеличить количество оперативной памяти компьютера, а также сменить процессор на более мощный. Кроме того, потребуется увеличить количество процессов httpd непосредственно в среде Apache. Может случиться и такое, что сайту вообще придется «переехать» на другой хостинг. Такая необходимость возникнет только в том случае, если сайт будет располагаться на обычном виртуальном хостинге, администратор которого либо не будет отвечать на запросы, либо откажется от помощи или если у него не получится решить такую проблему.

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

axios get request Error: Request failed with status code 504

here is my code that makes an Http Get request to an API end point from one of the services running on Amazon Fargate service. The API is powered by Amazon API gateway and Lambda. Also this is a private api used with in the VPC and I also have setup the apigateway VPC end point to facilitate the same. I have received this error only once. All the subsequent calls made to the API were successful.

My suspicion is that the lambda was not warm and that resulted a timeout. I am going to try setting a timeout for the axios code. any suggestions welcome

1 Answer 1

Turns out my lambda is timing out after the 30 seconds configured time. I could increase the lambda timeout, but the configurable timeout for API gateway is 30 seconds.

It has only happened once and i believe that it’s because lambda cold start. As a workaround, I am taking the retry approach. The API request will be retried 3 times.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Проблемы с DNS.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Параметры Nginx

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

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

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

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

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

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

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

Заключение

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Что обозначает ошибка 504

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

Сервера, у которых Apache установлен в качестве бэкенда, а nginx – фронтэнда, чаще всего генерируют данный код ошибки. Работа пользователя с сервером происходит по следующему плану: клиент отправляет запрос на сервер, который попадает не на прямую на Apache, а пересылается через nginx (это что-то вроде распределителя запросов). Если последний не смог получить ответ от Apache, за установленный промежуток времени, он отправляет клиенту вместо требуемого ему результата сообщение об ошибке сервера 504 (Gateway Timeout).

Причины появления ошибки

Нехватка ресурсов на сервере из-за большой нагрузки.

Сервер Apache имеет одну не очень приятную особенность – при большой нагрузке и нехватке ресурсов, он не успевает обрабатывать большое количество запросов и вовремя отдавать на них http-ответы. Таким образом, клиентские запросы выстраиваются в очередь, и когда лимит времени на получение ответа заканчивается, они сбрасываются ни с чем. Как следствие, пользователь видит на странице браузера код ошибки 504 (Gateway Timeout).

Ошибки, допущенные в скриптах.

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

Можно выделить следующие причины задержки исполнения скрипта:

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

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

3. Скрипт пытается установить соединение через прокси-сервер, который на данный момент недоступен и не может обработать запрос.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Способы устранения ошибки 504

Если шибка возникает из-за нагрузки на сервер, то в первую очередь необходимо предпринять следующие шаги:

1. Провести оптимизацию сервера.

2. Провести оптимизацию скриптов.

3. Увеличить доступные для сервера ресурсы (количество процессов httpd (Apache), оперативную память и т. п.)

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

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

Если есть подозрение на работу скриптов:

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

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

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

php_value max_execution_time N

Но делать это через файл htaccess позволяют не все хостеры.

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

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

504 Gateway Time-out что значит

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Что такое 504 Gateway Time-out и каковы её причины

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Причины ошибки 504 Gateway Time-out могут быть следующими:

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Заключение

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

Код 504: ошибка превышения времени ожидания отклика

Наверняка многие пользователи Интернета и компьютерных сетей не один раз сталкивались с такой неприятной ситуацией, как появление в браузере кода 504 (ошибка). Не все достаточно четко представляют себе, почему происходит такой сбой и как все это исправить. Давайте посмотрим, что к чему.

Что означает ошибка «504 Gateway time out»?

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Причины появления ошибки

Теперь, насколько это возможно максимально просто, затронем технический аспект. Итак, у нас появляется ошибка 504. Что значит такое сообщение с точки зрения взаимодействия терминала пользователя и удаленного сервера?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Понятно, что если nginx вовремя не получает ответа от Apache-сервера, он вместо ожидаемого результата и выдает пользователю сообщение с кодом 504 (ошибка). Впрочем, такие ситуации можно исправить, причем даже самым элементарным способом.

Код 504 (ошибка): как с этим бороться?

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как правило, это либо кнопка «Обновить», либо использование функциональной клавиши F5. Такое правило действует для всех браузеров без исключения. Возможен, правда, более долгий вариант, когда связь является нестабильной. Очень может быть, что в данном случае придется перезагрузить всю систему или даже маршрутизатор (в частности, при использования доступа в Интернет через Wi-Fi-подключение).

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

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

Проблемы при инсталляции приложений

Однако же и это еще не все. Достаточно часто может появляться ошибка при установке (код 504), когда приложение или программа инсталлируется непосредственно из сети Интернет. В данном случае дистрибутив не скачивается на винчестер, а находится на удаленном сервере, с которого и производится установка.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Заключение

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

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

504 Gateway Time-out because nuxt app is hanging #5090

Comments

kalenjordan commented Feb 21, 2019 •

Version

Reproduction link

Steps to reproduce

It’s happening right now on my app, but I will probably restart the app shortly so that it’s functional again. It seems to happen every 2 to 8 hours, and I’m not sure why, but the app simply stops responding.

Going to https://pros.global/ gives a 504 Gateway Time-out from nginx. If I access the nuxt app directly by going to http://pros.global:3000, it simply hangs forever.

The nuxt app would respond with something, at least an error message of some kind.

What is actually happening?

There is no response from the Nuxt app, it just hangs forever, causing nginx to 504 timeout.

Additional comments?

Also there isn’t anything being logged into sentry. This seems to be correlated with the axios 500 error that I posted about here: https://cmty.app/nuxt/nuxt.js/issues/c8707

The text was updated successfully, but these errors were encountered:

Как избавиться от ошибки 504 Gateway Time-out

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

504 gateway timeout – что это?

Естественно, что любую процедуру лечения рекомендуется начинать с понимания причин возникновения ошибки. Или, как минимум, знания определения каждой неприятности. Если сделать перевод на русский «504 gateway time out», то получиться сообщение, в котором говорится о шлюзе, к которому истекло время, отведенное для подключения.

То есть, выглядит это примерно так:

В итоге, возникает код ошибки 504 Gateway Time-out.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Как исправить 504 gateway time out nginx и ее аналоги

Существует три способа, которые могут помочь решить данную проблему.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Этот вариант подразумевает при возникновении 504 gateway timeout облегчить используемые скрипты, которые, кроме своих положительных качеств имеют и отрицательные. Например, увеличивают время подключения к удаленному серверу.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Кроме того, рекомендуется увеличить установленные значения для параметра PHP max_execution_time.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Ошибка 504 gateway time out для владельцев сайтов

Конечно, с данной ситуацией могут столкнуться не только владельцы серверов, но и те люди, которые держат на них свои сайты. Что делать в этом случае? Прежде всего, обратиться в службу поддержки, которая должна оперативно исправить ситуацию. Если этого не произошло или код ошибки 504 Gateway Time-out возникает с пугающей периодичностью, то выход из положения только один – переход на другого хостинг-провайдера, способного оградить владельца сайта от возникновения такой неприятности.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

504 Gateway Time-out

Есть скрипт на VPS, который выполняется раз в день. При выполнении ровно через 60 секунд выдает 504 Gateway Time-out в htaccess прописано: php_value max_execution_time 800 php_value max_input_time 800 php_value proxy_send_timeout 800 php_value proxy_read_timeout 800 php_value proxy_connect_timeout 750

и ничего не меняется, хоть phpini() и выдает верные значение куда копать?

2 ответа 2

Скорее всего Вы получаете ошибку 504 Gateway Time-out именно от сервера Apache, тогда можно попробовать поменять опцию Timeout, находится в файле конфигураций веб сервера, чаще всего это либо httpd.conf или httpd-default.conf. Найдите эти файлы и поменяйте этот параметр:

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

Как исправить ошибку «Тайм-аут 504 шлюза»

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Даже если виновник может показаться очевидным, как и в случае с большинством кодов ответов HTTP, большую часть времени будет трудно определить точную причину. С самого начала вы должны понимать, что ошибку 504 Gateway Timeout обычно нельзя исправить на стороне клиента. Как вы, вероятно, знаете, ошибки 5xx — это коды состояния для ошибок на стороне сервера, а 4xx — ошибки, происходящие на стороне клиента. Однако бывают случаи, когда что-то в вашей конфигурации запускает этот код состояния HTTP.

Помните, что вы можете видеть 504 несколько иначе. Вот список наиболее распространенных вариантов ошибки 404:

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Если вы столкнулись с ошибкой HTTP 504, лучше всего определить, есть ли у других такая же проблема. Это избавит вас от ненужных действий по устранению неполадок, когда проблема на самом деле связана с сервером. Вы можете сделать это, посетив тот же URL с другого устройства и используя другой мост для подключения к Интернету. Например, если вы получаете сообщение об ошибке при посещении веб-сайта со своего компьютера, переключите устройство Android/iOS на мобильные данные и перейдите по той же ссылке.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Метод 1. Перезагрузка страницы

Если вы посещаете веб-сайт с высоким трафиком, а хост/сервер перегружен и не может обработать ваш запрос.

Если это не работает, попробуйте потерять подкаталоги и посетите страницу индекса этого конкретного сайта.

Метод 2: выполните общий перезапуск

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

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

Метод 3: Удалите настройки прокси-сервера

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

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

Метод 4: Устранение проблем с DNS

Когда вы выходите в сеть, ваш провайдер автоматически назначает вам первичный и вторичный сервер. Ошибка 504 Gateway Timeout вполне может быть вызвана настройками DNS. Но имейте в виду, что если рассматриваемый сайт недавно перешел на новый хост, потребуется некоторое время, пока он не будет полностью распространен.

Однако проблема с DNS также может быть связана с клиентом — боковая сторона. Чтобы убедиться, что это не так, вы можете очистить локальный кеш DNS и посмотреть, исчезло ли сообщение об ошибке. Вот как можно очистить кеш DNS:

Заключение

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

How to add a fix to avoid 504 Gateway timeout error

I am getting 504 Gateway timeout error from my GET method call to another service. Recently I added a fix by increasing the timeout period but that didn’t help.

This is what I have tried

I am calling this process within a loop to process records, this works for most of the records but fails for few userId’s in that. But what I noticed is everything will work fine when I run only the failed records, not sure whats the problem in this case.

I thought of calling the method again when I receive 504 to invoke it again hoping to receive 200 next time.

Not sure is this the good idea. Any advice would be greatly appreciated.

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

According to the description of the 504 Gateway Timeout status code, it is returned when you have a chain of servers that communicate to process the request and one of the nodes (not the server you are calling but some later one) is not able to process the request in a timely fashion.

I would presume that the situation you are in could be depicted as follows.

The problem is that SOME OTHER SERVICE is taking too long to process your request. The USERS SERVICE gives up at some point in time and returns you this specific status code to indicate that.

As far as I know, there is little you could do to mitigate the problem. You need to get in touch with the owners of the USERS SERVICE and ask them to increase their timeout or the owners of SOME OTHER SERVICE and ask them to improve their performance.

Of course, all of these are speculations, without knowing you actual scenario.

Что такое ошибка тайм-аута шлюза 504 и как ее исправить

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Что такое ошибка тайм-аута шлюза 504

Аналогично кодам ошибок 4xx, например «Ошибка 404 страница не найдена», 504 Ошибка тайм-аута шлюза также является кодом состояния HTTP. Это ошибка на стороне сервера, которая указывает на то, что проблема вызвана сервером. Это происходит довольно часто, и почти каждый пользователь столкнулся бы с этим при попытке загрузить страницу.

Иногда случается, что вы можете увидеть разные формы ошибки 504 Gateway Timeout Error в разном количестве веб-браузеров. Однако все они имеют одно и то же значение. Вот несколько альтернативных имен ошибки 504 Gateway Timeout Error, с которой вы можете столкнуться. Вот они:

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

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

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

Рассмотрим их подробнее:

1]Обновить страницу

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

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

2]Перезагрузите все сетевые устройства.

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

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

3]Отключить настройки прокси

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

4]Измените свои DNS-серверы

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

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

5]Свяжитесь с сайтом

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

Представитель может хорошо объяснить вам правильные причины возникновения этой ошибки. Таким образом, вы можете избавиться от ошибки 504 Gateway Timeout Error.

6]Обратитесь к своему интернет-провайдеру.

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

7]Повторите попытку через некоторое время

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

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

Читайте дальше: Что такое ошибка тайм-аута 408 запроса?

Error 504 что это значит

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Вступление

Ошибка 504 gateway timeout – это один из кодов состояния HTTP, который сервер может вернуть, если он не смог завершить обработку запроса. Хотя эта ошибка и реже встречается, чем 500 internal server или 502 bad gateway, каждый сталкивался с ней, по крайней мере, пару раз, просматривая интернет. Это руководство посвящено тому, что собой представляет ошибка 504 и как её исправить.

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

Что такое ошибка 504 Gateway Timeout?

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Ошибка 504 gateway timeout также может иметь и другие формулировки, например:

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

В большинстве случаев причина ошибки 504 шлюз не отвечает исходит с серверной стороны, однако они также могут появляться и по причине проблем или неправильных конфигураций с пользовательской стороны. Таким образом, мы рассмотрим основные этапы устранения неполадок с учётом обоих вариантов. Часть решений подходит для WordPress, но большинство из них могут быть применены к любому веб-сайту.

1. Обновите страницу

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

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

2. Попробуйте другой браузер

В случае, если сайт онлайн, однако вы всё равно видите ошибку 504 gateway timeout, попробуйте сменить свой браузер на другой. Очистите кэш браузера или воспользуйтесь режимом incognito, это тоже может помочь определить, связана ли причина проблемы с браузером.

3. Очистите кэш DNS

Ошибка 504 gateway timeout иногда может быть результатом некорректного устаревшего кэша DNS, но его не сложно очистить. Способ очистки зависит от вашей операционной системы. Вот руководство как очистить кэш DNS в ОС Windows, Linux и Mac OS.

Временно переключите DNS сервера на Google Public DNS, это поможет определить возник ли код состояния HTTP по причине DNS проблемы. Однако мы рекомендуем этот вариант для более опытных пользователей.

4. Проверьте на разных устройствах

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

5. Посмотрите журнал ошибок

Ошибка 504 gateway timeout может также быть вызвана недавними изменениями или обновлениями на сайте. Самый быстрый путь обнаружения – проверка журнала ошибок (англ.) для поиска подсказок. Пользователи WordPress могут включить журналирование ошибок добавлением таких строк в файл wp-config.php:

Теперь все возникающие варианты ошибок будут появляться в файле wp-contents/debug.log.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

Для отключения всех плагинов WordPress перейдите в каталог wp-content, дайте каталогу plugins другое имя.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

7. Проверьте CDN

Если вы используете CDN для более быстрого получения контента, то обязательно проверьте всё ли в порядке с этой стороны. Самый распространённый случай – это CloudFlare, который работает как CDN и как сервис предотвращения негативных последствий от DDoS. При его использовании вы можете столкнуться в двумя видами ошибок 504 gateway timeout.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

8. Измените настройки сервера

Если вы используете VPS хостинг, то есть ещё несколько дополнительных моментов, которые вы можете попробовать для исправления ошибки 504 gateway timeout. Они будут заключаться в изменении настроек сервера и увеличении лимитов некоторых ресурсов.

Apache

Пользователи Apache могут увеличить значение timeout по умолчанию в файле httpd.conf. Например:

Также увеличение лимита max_execution_time в php.ini может позитивно сказаться:

Сохраните изменения и перезапустите apache, после чего проверьте. Ошибка 504 gateway timeout должна уйти, если её причиной были недостаточное значение таймаута запроса.

Nginx

Если ваш VPS использует Nginx, попробуйте увеличить такие параметры в файле /etc/nginx/conf.d/timeout.conf:

Также рекомендуется увеличить max_execution_time в php.ini:

После сохранения изменений перезапустить Nginx и попробуйте ещё раз открыть свой сайт.

9. Свяжитесь со службой поддержки

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

Выводы

В этом руководстве мы рассмотрели общие шаги для решения проблемы, связанной с ошибкой 504 gateway timeout. Если у вас есть свои хитрости, подсказки или дополнительные решения для устранения этого кода состояния HTTP, дайте нам знать в комментариях!

При заходе на сайт выдается ошибка 504 Gateway Timeout Error. Как ее исправить?

Ответ

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Существует несколько способов для решения проблемы.

Способ 1. Перезагрузка страницы в веб-браузере

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Способ 2. Отключение параметров прокси

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

Способ 3. Проверка службы DNS

Ошибка 504 Gateway Timeout Error также может быть вызвана проблемами с DNS-службой, а именно на сервере, когда, например, домен не преобразован в корректный IP. Часто такое случается, если Вы только что перенесли свой сайт с локального компьютера на хостинг. В таком случае необходимо дождаться распространения DNS-данных по всей Сети (обычно до 48 часов).

Наконец, Вы вправе на какое-то время изменить DNS-сервера Вашего хостинга на публичные (например, 8.8.8.8 или 8.8.4.4 от Google).

Способ 4. Временное отключение CDN

Иногда ошибка 504 может появляться вследствие использования прокси-серверов типа Cloudflare или Sucuri. Например, для первого сервиса существует два типа ошибки 504.

Вариант 1

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

В этом случае проблема действительно со службой Cloudflare. Для ее решения нужно обратится в техподдержку сервиса.

Вариант 2

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Способ 5. Проверка хостинга

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

Способ 6. Проверка и выявление спама, вирусов и DDoS-атак

Еще одна причина возникновения ошибки 504 – это наличие спама, вируса или DDoS-атаки, что может привести к перегрузке и отказу сервера. В таком случае необходимо, во-первых, ознакомится с предоставляемыми компанией-хостингом инструментами для борьбы с вышеперечисленными угрозами. Часто в админ-панели хостинга присутствуют антивирус, а также включение защиты от DDoS-атак. Что касается спам-комментариев на сайте WordPress, то с этим довольно эффективно борются соответствующие плагины (например, самый популярный среди пользователей Akismet Anti-Spam ). Для выявления угроз обычно изучают статистику сервера, статистику поисковых систем на предмет подозрительных IP-адресов.

Способ 7. Проверка активных тем и плагинов

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Ошибка 504 (Gateway Time Out) это http код, который означает, что сайт или приложение, к которому вы обращаетесь, не успел обработать данные в отведённое ему время. Обычно это время (timeout) устанавливается сервером. В данной статье я расскажу как можно исправить ошибку 504 Gateway Timeout или, по крайней мере, избежать её. Чтобы понять суть этой ошибки, представьте следующую ситуацию: вы хотите узнать штрафы для своего автомобиля.

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

Примерно так выглядит ошибка 504. Ещё вариант — вы загружаете большое фото, которое сервер неспособен обработать быстро. Результат — 504 Gateway Time Out. По большому счёту, вы никак не можете исправить ошибку самостоятельно, если вы не владеете сервером. Однако, вы в силах предотвратить её появление, изменив свои действия. Например, если вы понимаете, что ошибка возникает при загрузке большой фотографии, попробуйте изменить её размер.

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

Что значит 504 gateway time out

Обычно ошибка 504 означает ошибку на стороне сервера, однако что делать, если вы единственный, у кого она происходит? Или что делать, если она выходит на всех сайтах? Разберём несколько вариантов решения проблемы с ошибкой 504:

Если на вашем сайте ошибка 504

Так как на данный момент лидирующим является WordPress, мы будем рассматривать решение проблемы с ошибкой 504 именно на этой CMS.

Теперь все возникающие ошибки будут отображаться в wp-contents/debug.log

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

Если у вас VPS, к которому вы имеете полный доступ, можно попробовать увеличить значение timeout.

Apache

Отредактируйте файл httpd.conf, изменив значение параметра timeout:

Кстати в OS X файл httpd.conf находится здесь: /Applications/XAMPP/xamppfiles/apache2/conf/httpd.conf

Nginx

Если у вас Nginx, то попробуйте изменить параметры в файле /etc/nginx/conf.d/timeout.conf:

Также увеличьте значение max_execution_time в файле php.ini

Однако, необходимо понять, что этот путь решения проблемы не совсем верен. Если время выполнения скрипта превышает допустимые значения, обратите внимание на уменьшение этого времени. Таким образом, ваши посетители и сервер скажут вам спасибо. Если по каким-то причинам это невозможно, задумайтесь об увеличении ресурсов сервера или кешировании (W3 Total Cache или другие плагины).

504 (Gateway Time Out) на хостинге

Обычно хостеры не дают менять параметры httpd и php, однако если у вас хороший хостинг, то вам обязательно помогут разобраться с проблемой и в конце концов ваш сайт заработает правильным образом. Кстати, ошибка 504 вполне может возникать из-за «плохого» хостинга и ваши усилия ни к чему не приведут. Кстати, на хостинге beget ваш сайт бесплатно перенесут и дадут первый месяц бесплатного размещения. Мой всё свое время находится на нём и я не знаю бед.

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

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

С уважением, редакция FixErro.com

Задайте вопрос

или поделитесь своим способом решения проблемы

Что значит ошибка 504 Gateway Time-out?

Не могу уже несколько часов просмотреть личное сообщение на этом сайте. Каждый раз выползает ошибка 504 Gateway Time-out. В чем дело: это что-то с сайтом или с моим браузером?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как понять перегрузку? У каждого сайта есть определенное количество места, которое он купил у хостинга. Это место заполняется контентом или расходуется пользователями (если это форум или ресурс с живым участием пользователя). Проект не может стоять на месте он обязан развиваться, дабы не ударить в АГС от робота. Для этого привлекаются еще пользователи для увеличения числа уникальных посетителей или увеличивается контент, который тоже занимает место, хоть и меньше.

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

Как устранить? Увеличить место за счет хостинга или искать зараженные файлы, которые извещают о перегрузке ресурса (если вы уверены, что не занимаете тот объем, который оплатили).

Ошибка 504 gateway time out — что значит почему она возникает и как ее исправить?

Summary

Your WordPress 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 WordPress site, leave a comment below.

Save time, costs and maximize site performance with:

All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.

Очистите кеш DNS.

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

Ошибка тайм-аута может возникнуть, если веб-сайт изменит свой IP-адрес или сервер. Это связано с тем, что кеш DNS направит ваш браузер на старый (или устаревший) IP-адрес. Вы можете решить эту проблему, очистив кеш DNS. Это побудит ваше устройство и браузер получить обновленную информацию DNS при следующем посещении веб-сайта.

Чтобы очистить кеш DNS на Mac, запустите Терминал (перейдите в Приложения> Утилиты> Терминал), вставьте команду ниже в консоль и нажмите Return.

При появлении запроса введите пароль вашего Mac и нажмите Return.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Для устройств Windows запустите командную строку (нажмите Windows + X и выберите Командная строка (администратор)), вставьте команду ниже в консоль и нажмите Enter.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Nginx

Nginx — это свободный, с открытым исходным кодом, высокопроизводительный HTTP-сервер и прокси-сервер, а также IMAP/POP3 прокси-сервер. В отличие от традиционных серверов Nginx не использует потоки для обработки запросов. Вместо этого он использует гораздо более масштабируемую, управляемую событиями (асинхронную) архитектуру. Эта архитектура под высокой нагрузкой использует небольшой, и главное, предсказуемый объем памяти.

Связка Phalcon + Nginx + PHP-FPM предоставляет мощный набор инструментов, который позволяет добиться максимальной производительности ваших PHP приложений.

Установка Nginx

Nginx — это бесплатный высокопроизводительный HTTP-сервер с открытым исходным кодом и обратный прокси-сервер, а также прокси-сервер IMAP / POP3. В отличие от традиционных серверов, Nginx не использует потоки для обработки запросов. Вместо этого он использует гораздо более масштабируемую управляемую событиями (асинхронную) архитектуру

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

Phalcon с Nginx и PHP-FPM предоставляют мощный набор инструментов, которые обеспечивают максимальную производительность для ваших приложений PHP.

Настройка под Phalcon

Вы можете использовать следующую конфигурацию Nginx для работы с Phalcon, вероятнее всего на вам подойдёт:

Запуск Nginx

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как исправить ошибку 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 gateway time out Nginx?

Самый первый вариант — это если вашему серверу, php-fpm или apache не хватает ресурсов системы, например, памяти или процессора. Вы можете посмотреть свободную память с помощью команды free:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Нагрузку на процессор можно узнать командой htop:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Второй вариант — это если так и было запланировано, чтобы скрипт работал долго. В таком случае нужно настроить Nginx, чтобы он дождался ответа от Apache или php-fpm. Для решения проблемы в случае с php-fpm нужно только добавить две строчки в блок настройки fastgci:

fastcgi_send_timeout 300; fastcgi_read_timeout 300;

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Здесь 300 означает 300 секунд, для большинства скриптов, этого будет вполне достаточно, но вы можете еще больше увеличить значение если это нужно. Также ошибка 504 может возникать, когда Nginx используется в качестве прокси для Apache или любого другого веб-сервера, тогда нужно еще настроить время ожидания для прокси. Добавьте эти строки в секцию server:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

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

sudo systemctl restart nginx

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

Более подробную информацию иногда можно увидеть в error.log:

Дальше, если проблема именно в php-fpm, вы можете отследить какие скрипты выполняются медленно с помощью встроенной функции slow-log. Для ее активации добавьте следующие строки в конфигурацию вашего пула:

sudo vi /etc/php-fpm.d/www.conf

slowlog = /var/log/php-fpm/www-slow.log request_slowlog_timeout = 5s

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

504 (Gateway Time Out) на хостинге

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

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

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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 means that the server processed the request successfully and “Everything is OK.”

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

The Internet Engineering Task Force (IETF) defines the as:

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:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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:

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

9: Поддержка HTTPS с помощью Let’s Encrypt (опционально)

Теперь нужно создать SSL-сертификаты для сайтов Apache. Получите бесплатные доверенные сертификаты от Let’s Encrypt.

Nginx поддерживает терминацию SSL, потому можно настроить SSL, не изменяя настроек Apache.

Модуль mod_rpaf установит все переменные Apache, необходимые для поддержки SSL.

Для начала создайте для обоих доменов блок server <…>, чтобы у каждого из них был свой сертификат. Откройте /etc/nginx/sites-available/apache:

Отредактируйте файл, создав блок server для foobar.net and test.io:

Сертификаты TLS/SSL можно сгенерировать с помощью Certbot. Его плагин для Nginx автоматически перенастроит веб-сервер и обновит конфиг.

Установите официальный репозиторий Certbot:

Чтобы подтвердить действие, нажмите ввод. Затем обновите индекс пакетов.

Теперь можно установить Certbot для Nginx:

Затем используйте команду certbot, чтобы сгенерировать сертификаты для foobar.net и www.foobar.net:

С помощью этой команды Certbot сможет использовать плагин nginx; флаг –d позволяет указать домены, для которых предназначен сертификат.

Если это ваш первый запуск certbot, вам будет предложено ввести адрес электронной почты и согласиться с условиями обслуживания. После этого certbot свяжется с сервером Let’s Encrypt, а затем запустит проверку, чтобы убедиться, что домен, для которого вы запрашиваете сертификат, действительно принадлежит вам.

Затем Certbot спросит, нужно ли настроить HTTPS:

Сделайте свой выбор и нажмите ввод. Конфигурации обновятся, а Nginx будет перезапущен. Теперь запустите команду для второго домена:

На появившейся странице найдите раздел PHP Variables. Для переменной SERVER_PORT установлено значение 443, а HTTPS — on, как если бы веб-сервер Apache был напрямую доступен через HTTPS.

Теперь давайте отключим прямой доступ к Apache.

Что значит 504 gateway time out

Обычно ошибка 504 означает ошибку на стороне сервера, однако что делать, если вы единственный, у кого она происходит? Или что делать, если она выходит на всех сайтах? Разберём несколько вариантов решения проблемы с ошибкой 504:

Часто задаваемые вопросы по теме статьи (FAQ)

При использовании https нужно ли в режиме proxy_pass настраивать https и на бэкенде?

В общем случае не обязательно. Но есть некоторый софт, который не может корректно работать в таком режиме. Он не понимает, как корректно обрабатывать такую ситуацию. Может создавать ссылки вида http://site.ru:443, которые будут являться ошибочными. В таком случае необходимо настроить обмен между nginx и бэк сервером тоже https соединение.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504 Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как наиболее простым спосбом передавать сертификат let’s encrypt с nginx на backend? Ведь обновдление и генерация сертификата происходят только на nginx.

Я в таких случаях использую 2 способа, в зависимости от ситуации. Самый простой — на сервере с nginx настроить nfs сервер, а на бэкенде подмонтировать по nfs к себе директорию /etc/letsencrypt и спокойно использовать сертификаты, как-будто они лежат локально. Второй вариант — использовать простой bash скрипт для копирования сертификатов к себе на сервер по scp. В обоих случаях надо не забыть на бэкенде перезапускать службы, которые использую сертификат, после его обновления.

При обращении с бэкенда по адресу сайта, запрос уходит на nginx proxy, так как в dns прописан его ip адрес. Из-за этого иногда не работают встроенные скрипты или проверки некоторых движков, так как они ожидают, что запрос вернется с того же сервера, с которого он был сделан. Но на практике он уходит на proxy и приходит оттуда.

В такой ситуации может помочь правка файла /etc/hosts на самом бэкенде. Сделайте там статическую запись с именем сайта и локальным ip адресом. Тогда запросы с самого сервера будут приходить на него же локально, а не на nginx proxy.

Что лучше использовать для проксирования http запросов nginx или haproxy?

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

Добавляет ли nginx в режиме proxy_pass дополнительные сетевые задержки?

Конечно да. Но на практике они очень малы, если nginx и целевой сервер находятся в общей локальной сети. С учетом задержек при передачи пакетов по сети интернет, этими локальными задержками можно пренебречь. Они будут ничтожно малы. Если же вы проксируете запросы через интернет, то нужно внимательно смотреть величину задержек между nginx и бэкендом. Желательно их делать минимальными, располагая сервера поближе друг к другу.

Как это будет работать?

Допустим, у нас есть несколько доменов example.com, sample.org, test.io. Первые два будут обрабатываться Apache, последний только Nginx. Все запросы будут поступать к Nginx, который работает на порту 80, если это запрос к одному из доменов Apache и он требует работы PHP, тогда он будет передан веб-серверу Apache, который работает на порту 8080.

Если же это запрос статического файла, то мы будем обрабатывать его тут же с помощью Nginx для увеличения производительности. Что касается поддержки SSL, то мы собираемся использовать модуль mod_pref чтобы заменить все необходимые заголовки для нормальной работы связки. Начнем с настройки Apache.

HTTP 504 (Gateway Timeout): How to fix an error 504

When you launch a website with your browser, the web server is usually only the last link in a chain of systems that deal with the processing of HTTP requests that have been sent. Network gateways and proxy servers regulate the forwarding, or even the answering, of a query to absolve the web server and guarantee a quick transfer of data. In other words, the server that is contacted is one that has several communications stations prefixed, something which is generally done for practical reasons. However, if it so happens that one of the prefixed systems malfunctions, this can lead to the query failing. Instead of the desired page, your browser will display an error message like ‘HTTP Error 504’ or ‘Gateway Timeout’.

Here you can find out what exactly is behind this type of server notification, and how to go about fixing a 504 Gateway Error message (as a client user or website operator).

HTTP 504: What’s behind the hypertext transfer protocol status code

The Hypertext Transfer Protocol is one of the most important protocols when it comes to the transfer of web content. Operating on the application layer, it initiates communication between the client – normally an internet browser – and the corresponding web server hosting the desired content. For this reason, HTTP communicates the website’s hypertext, which the client software can in turn convert into text, images, etc. This exchange occurs via notifications through which the client defines a HTTP request. The server then responds to this with an answer that includes a 504 status code, which for example might include information on a successful processing (HTTP 200), or else information on its failure, in the case of a 504 error.

The HTTP 504 response lets the client know that the cause of the failure was due to a timeout during the processing of a request. This is why the message code also displays the designation ‘Gateway Timeout’. The sender of the message is the server in the communication chain that was unable to fulfil its function as a gateway, or proxy, as it didn’t receive a response from the next server (or service) within a specific time. Exactly how the error message is displayed in the browser window is something which the website operator can decide for themselves. Examples of frequently used 504 error messages are:

Why do 504 Gateway Timeouts occur?

HTTP 504 messages always occur when an intermediary server, or rather a network interface, cannot respond to the browser’s query within a clearly specified time. As has already been mentioned, this results in the affected system to not receive a response from the next link in the chain. There are several reasons why this might occur:

1. The proxy server or router in the local network, upon which the user relies, are overburdened or have even crashed, and therefore are no longer working. In this case, the 504 error is rarely limited to a single web project, but will also occur when other pages are launched.

2. The launched website will revert to a proxy server for performance optimization. However, this server is overwhelmed, or has perhaps even crashed, and can therefore no longer be reached by prefixed internet nodes – leading in turn to a gateway timeout.

3. Sometimes the incorrect proxy settings, both on the client’s side as well as the server’s, can be responsible for the appearance of a HTTP 504 message.

4. The problem affects one or several of an internet provider’s or company’s servers. This means that the inaccessibility has nothing to do with the browser user’s router or proxy settings, or indeed that of the operator of the website in question.

How to fix a 504 Gateway Timeout Error

If the requested page fails to load and instead a 504 error page appears, this is very frustrating for every user. Even more so, if the service is being used for an issue of great importance, meaning that the frustration around the timeout can quickly lead to full-on anger. Especially if you are working with cloud applications and therefore have no offline alternative available, you become very reliant on a timely solution. The same applies if you are responsible for a web project, which becomes inaccessible to users as a result of gateway timeout problems. In this case, a quick reaction is important to limit the loss of traffic to the website, and in turn, damage its turnover.

504 Gateway Timeout: How to fix the problem as a browser user

If you encounter a HTTP error 504 during your daily online activity, then it is safe to assume this is not intentional. Unlike, for example, if maintenance work is taking place when a 503 status code is displayed. A gateway timeout is nearly always a result of a server problem on part of the website operator or provider. Although as was already mentioned, it is also possible that your router or one of your own proxy settings is responsible for the error message. This means that as a browser user you have various options for fixing a HTTP 504 error:

Option 1: Reload the desired web application

In most cases, a 504 error will only appear for a pretty short time. A quick and easy option for fixing a 504 gateway timeout is therefore to simply refresh the desired web page. All that is required to this is one click on ‘Reload’ button in the address bar of the browser. This can also be done by pressing [F5] or [Ctrl] + [R]. Alternatively, you can also enter the URL again.

Option 2: Restart all network devices

If it is the case that the timeout has occurred within a home network, the problem can often be solved by resetting all your network devices. It may have happened that the modem, router, etc. has been configured incorrectly, or are failing to work properly due to other reasons, and therefore the browser’s HTTP request cannot be carried out in the specified time period. A clear sign that this is the problem is if you are unable to launch other websites as well, and instead are being met with a HTTP 504 error message.

In order to protect your privacy, the video will not load until you click on it.

Option 3: Review your proxy server settings

If you use a proxy server for your internet activity, and you are unable to fix a 504 error by refreshing the page or restarting the browser, and you should check the relevant settings in your browser. For one, it could be that the configuration is defective. It could also be necessary for you to select a different proxy, because the server that you have been using up until this point is no longer available or is experiencing technical issues – although it is usually the case that specific messages like ‘Proxy server not responding’ or ‘Proxy server refusing connection’ are displayed. Our guide tells you how to adjust your proxy settings in your browser.

Option 4: Changing the DNS server

It may also be the case that the DNS server being used by the router could be responsible for the 504 gateway timeout. As soon as you connect and go online, your internet provider automatically assigns you a primary and secondary server – but it is also possible for you to choose your own name resolution. Both varieties are in no way fail proof, meaning that experiencing a timeout while connecting to the DNS server is something that is always possible. In such a situation, a change to a different, free, and publicly available DNS server could be the perfect solution. Our digital guide tells you which necessary steps need to be taken for changing DNS server.

Option 5: Get in contact with the website operator and/or your provider

It may be that you have no success with changes to your own hardware and software, and in this case, you should get directly in touch with the operator of the website or the administrator responsible for the site. It may be that the cause of the HTTP 504 error lies with the web project itself. This way you will find out what the problem is straight from the horse’s mouth, as well as when the website is expected to be back in action. If the error is only happening to you or a specific group of users, then it is very likely that there is a problem with your internet provider. If this is the case then you have no other choice but to get in contact with them.

If the website in question is one that is very popular, then it could be worth having a look at social media, e.g. Twitter. Companies regularly use this medium to communicate any current problems that they or their website are experiencing. Furthermore, this is also a way for you to find out quickly whether other users are effected by the same issue. In cases like this, hashtags like #websitedown (e.g. #facebookdown) will often start trending quickly.

Option 6: Try again later

Regardless of which server in the chain of communication is effected, or regardless of the reason why it cannot further process the query, there is nothing that individual measures like restarting, etc. can do to solve a HTTP error 504. You simply have to wait until the website operator or indeed the provider responsible has fixed the issue. If a website displays the error message for a longer time, or even in regular intervals, then it is recommended that you save yourself from any more hassle and simply return to the website at a later time.

504 error: Here are the possible solutions for website operators

As the operator of a web project you want to be able to give your visitors the best possible content and very good usability, as well as also guaranteeing a high level of availability. A stable hosting environment and protection from malware, spam, etc. are equally as important as being able to react quickly to technical problems, like 504 gateway timeouts. Ideally you should be able to discover an issue like this as quickly as possible and then immediately set about identifying the cause, as well as finding the right solution.

Option 1: Increase your proxy server resources

In many cases, one’s own proxy server can be the cause of a HTTP error 504. So, if it is the case that you also use a proxy for your website, in order to relieve the web server, then it could be that this is responsible for the gateway timeout. It may also depend on whether the project has grown dramatically in a short amount of time and visitor numbers have shot up, and at the same time, whether the proxy has necessary resources for processing the HTTP requests. The same applies to isolated peak times, which are due, for example, to seasonal events such as Christmas.

If it is the case that your visitor numbers have increased and 504 error messages are appearing at times when traffic is very high, then this is a pretty clear indicator that the server is overloaded. Here the solution is to purchase additional hardware resources or to book them from your internet provider. Ideally the provider in question would take care of such an increase in advance, meaning that you can avoid any timeout as a result of insufficient server power/space. This is especially easy if you opt for a flexible solution like cloud hosting from the start. This allows you to provide your proxy server with permanent or temporary additional power, so that all incoming HTTP requests can be processed without any danger of problems or, more importantly, 504 error messages.

HTTP 504 (Gateway Timeout): How to fix an error 504

When you launch a website with your browser, the web server is usually only the last link in a chain of systems that deal with the processing of HTTP requests that have been sent. Network gateways and proxy servers regulate the forwarding, or even the answering, of a query to absolve the web server and guarantee a quick transfer of data. In other words, the server that is contacted is one that has several communications stations prefixed, something which is generally done for practical reasons. However, if it so happens that one of the prefixed systems malfunctions, this can lead to the query failing. Instead of the desired page, your browser will display an error message like ‘HTTP Error 504’ or ‘Gateway Timeout’.

Here you can find out what exactly is behind this type of server notification, and how to go about fixing a 504 Gateway Error message (as a client user or website operator).

HTTP 504: What’s behind the hypertext transfer protocol status code

The Hypertext Transfer Protocol is one of the most important protocols when it comes to the transfer of web content. Operating on the application layer, it initiates communication between the client – normally an internet browser – and the corresponding web server hosting the desired content. For this reason, HTTP communicates the website’s hypertext, which the client software can in turn convert into text, images, etc. This exchange occurs via notifications through which the client defines a HTTP request. The server then responds to this with an answer that includes a 504 status code, which for example might include information on a successful processing (HTTP 200), or else information on its failure, in the case of a 504 error.

The HTTP 504 response lets the client know that the cause of the failure was due to a timeout during the processing of a request. This is why the message code also displays the designation ‘Gateway Timeout’. The sender of the message is the server in the communication chain that was unable to fulfil its function as a gateway, or proxy, as it didn’t receive a response from the next server (or service) within a specific time. Exactly how the error message is displayed in the browser window is something which the website operator can decide for themselves. Examples of frequently used 504 error messages are:

Why do 504 Gateway Timeouts occur?

HTTP 504 messages always occur when an intermediary server, or rather a network interface, cannot respond to the browser’s query within a clearly specified time. As has already been mentioned, this results in the affected system to not receive a response from the next link in the chain. There are several reasons why this might occur:

1. The proxy server or router in the local network, upon which the user relies, are overburdened or have even crashed, and therefore are no longer working. In this case, the 504 error is rarely limited to a single web project, but will also occur when other pages are launched.

2. The launched website will revert to a proxy server for performance optimisation. However, this server is overwhelmed, or has perhaps even crashed, and can therefore no longer be reached by prefixed internet nodes – leading in turn to a gateway timeout.

3. Sometimes the incorrect proxy settings, both on the client’s side as well as the server’s, can be responsible for the appearance of a HTTP 504 message.

4. The problem affects one or several of an internet provider’s or company’s servers. This means that the inaccessibility has nothing to do with the browser user’s router or proxy settings, or indeed that of the operator of the website in question.

How to fix a 504 Gateway Timeout Error

If the requested page fails to load and instead a 504 error page appears, this is very frustrating for every user. Even more so, if the service is being used for an issue of great importance, meaning that the frustration around the timeout can quickly lead to full-on anger. Especially if you are working with cloud applications and therefore have no offline alternative available, you become very reliant on a timely solution. The same applies if you are responsible for a web project, which becomes inaccessible to users as a result of gateway timeout problems. In this case, a quick reaction is important to limit the loss of traffic to the website, and in turn, damage its turnover.

504 Gateway Timeout: How to fix the problem as a browser user

If you encounter a HTTP error 504 during your daily online activity, then it is safe to assume this is not intentional. Unlike, for example, if maintenance work is taking place when a 503 status code is displayed. A gateway timeout is nearly always a result of a server problem on part of the website operator or provider. Although as was already mentioned, it is also possible that your router or one of your own proxy settings is responsible for the error message. This means that as a browser user you have various options for fixing a HTTP 504 error:

Option 1: Reload the desired web application

In most cases, a 504 error will only appear for a pretty short time. A quick and easy option for fixing a 504 gateway timeout is therefore to simply refresh the desired web page. All that is required to this is one click on ‘Reload’ button in the address bar of the browser. This can also be done by pressing [F5] or [Ctrl] + [R]. Alternatively, you can also enter the URL again.

Option 2: Restart all network devices

If it is the case that the timeout has occurred within a home network, the problem can often be solved by resetting all your network devices. It may have happened that the modem, router, etc. has been configured incorrectly, or are failing to work properly due to other reasons, and therefore the browser’s HTTP request cannot be carried out in the specified time period. A clear sign that this is the problem is if you are unable to launch other websites as well, and instead are being met with a HTTP 504 error message.

In order to protect your privacy, the video will not load until you click on it.

Option 3: Review your proxy server settings

If you use a proxy server for your internet activity, and you are unable to fix a 504 error by refreshing the page or restarting the browser, and you should check the relevant settings in your browser. For one, it could be that the configuration is defective. It could also be necessary for you to select a different proxy, because the server that you have been using up until this point is no longer available or is experiencing technical issues – although it is usually the case that specific messages like ‘Proxy server not responding’ or ‘Proxy server refusing connection’ are displayed. Our guide tells you how to adjust your proxy settings in your browser.

Option 4: Changing the DNS server

It may also be the case that the DNS server being used by the router could be responsible for the 504 gateway timeout. As soon as you connect and go online, your internet provider automatically assigns you a primary and secondary server – but it is also possible for you to choose your own name resolution. Both varieties are in no way fail proof, meaning that experiencing a timeout while connecting to the DNS server is something that is always possible. In such a situation, a change to a different, free, and publicly available DNS server could be the perfect solution. Our digital guide tells you which necessary steps need to be taken for changing DNS server.

Option 5: Get in contact with the website operator and/or your provider

It may be that you have no success with changes to your own hardware and software, and in this case, you should get directly in touch with the operator of the website or the administrator responsible for the site. It may be that the cause of the HTTP 504 error lies with the web project itself. This way you will find out what the problem is straight from the horse’s mouth, as well as when the website is expected to be back in action. If the error is only happening to you or a specific group of users, then it is very likely that there is a problem with your internet provider. If this is the case then you have no other choice but to get in contact with them.

If the website in question is one that is very popular, then it could be worth having a look at social media, e.g. Twitter. Companies regularly use this medium to communicate any current problems that they or their website are experiencing. Furthermore, this is also a way for you to find out quickly whether other users are effected by the same issue. In cases like this, hashtags like #websitedown (e.g. #facebookdown) will often start trending quickly.

Option 6: Try again later

Regardless of which server in the chain of communication is effected, or regardless of the reason why it cannot further process the query, there is nothing that individual measures like restarting, etc. can do to solve a HTTP error 504. You simply have to wait until the website operator or indeed the provider responsible has fixed the issue. If a website displays the error message for a longer time, or even in regular intervals, then it is recommended that you save yourself from any more hassle and simply return to the website at a later time.

504 error: Here are the possible solutions for website operators

As the operator of a web project you want to be able to give your visitors the best possible content and very good usability, as well as also guaranteeing a high level of availability. A stable hosting environment and protection from malware, spam, etc. are equally as important as being able to react quickly to technical problems, like 504 gateway timeouts. Ideally you should be able to discover an issue like this as quickly as possible and then immediately set about identifying the cause, as well as finding the right solution.

Option 1: Increase your proxy server resources

In many cases, one’s own proxy server can be the cause of a HTTP error 504. So, if it is the case that you also use a proxy for your website, in order to relieve the web server, then it could be that this is responsible for the gateway timeout. It may also depend on whether the project has grown dramatically in a short amount of time and visitor numbers have shot up, and at the same time, whether the proxy has necessary resources for processing the HTTP requests. The same applies to isolated peak times, which are due, for example, to seasonal events such as Christmas.

If it is the case that your visitor numbers have increased and 504 error messages are appearing at times when traffic is very high, then this is a pretty clear indicator that the server is overloaded. Here the solution is to purchase additional hardware resources or to book them from your internet provider. Ideally the provider in question would take care of such an increase in advance, meaning that you can avoid any timeout as a result of insufficient server power/space. This is especially easy if you opt for a flexible solution like cloud hosting from the start. This allows you to provide your proxy server with permanent or temporary additional power, so that all incoming HTTP requests can be processed without any danger of problems or, more importantly, 504 error messages.

504 Gateway Timeout from an IIS Server

I am using a web Server based on IIS,I am using an Infor Application which is trying to fetch data from the Web Server. However when there is a lot of data and the query runs more than 60 seconds, i get a Gateway Timeout Error(504).

Where do i set the configuration to increase till say 2 minutes or 5 minutes? Any Help would be appreciated.

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If as the other answer suggests, you are using ARR, there is another undocumented setting which often causes 502’s

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

It sounds like you have ARR installed. If you do, you can change the timeout setting by following these steps:

Another place this could be set is under Server Farms in IIS Manager. Choose the Server Farm and click Proxy. Set the time-out (seconds) to a larger value.

Ошибка 504 Gateway Time-out: что значит и как исправить?

Поступило сообщение — ошибка 504. Это говорит о том, что шлюз долго отвечал или завершился раньше времени.

Причины 504 ошибки.

Рассмотрим основные причины. Это может быть нехватка оперативной памяти на сервере, проблемы со скриптами на вашем сайте, проблемы с настройкой сервера и т. д. Элементарная причина появления ошибки 504 — перегрузка сервера, в результате чего создается очередь из запросов. Из-за ожидания в очереди запрос не поступает на обработку за отведенное время и сбрасывается.

Смена площадки для сайта поможет решить проблему лишь на некоторое время. Насущная рекомендация — заняться оптимизацией (настроек сервера, скриптов, запросов SQL). Следует также подумать об увеличении ресурсов сервера, поиске другого хостинга. Рекомендуется обратиться в службу консультации вашего хостинга. Но это лучше сделать после оптимизации скриптов сайта.

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

Решение ошибки.

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

Чтобы увеличить его, можно применить set_time_limit. Только не всегда удается задействовать эту схему из-за ограничений на хостинге. Если PHP запущен в так называемом безопасном режиме, то нужно в конфигурации php увеличить время работы скрипта(функция max_execution_time). Когда же не удается снять запрет на использование set_time_limit, попробуйте запустить данную функцию (max_execution). Наконец, можно в конфигурации сервера увеличить время работы скрипта. Для этого прописать следующее:

Ставим 60 с (120) вместо 30с стоящих по умолчанию.

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

How to Fix 504 Gateway Timeout Error: 10 Reliable Solutions

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Like the 500 internal server and 502 bad gateway errors, 504 “Gateway Timeout” is one of the most common server errors both users and website owners encounter.

Every second of downtime can harm your WordPress site’s search engine performance. Therefore, as a website owner, you need to fix this issue as soon as possible.

Debugging the 504 gateway timeout error can be challenging due to the high number of potential causes. In most cases, you can resolve it by refreshing the web page.

This article will go over the possible causes of the 504 gateway timeout error. We’ve included troubleshooting tips to help you get the site up and running in no time.

Error code504 Gateway Timeout Error
Error typeServer-side
Error variationsGateway Timeout Error
Gateway Timeout (504)
504 Gateway Time-out. The server didn’t respond in time
This page isn’t working. Domain took too long to respond
HTTP Error 504 – Gateway Timeout
504 Status Code
Error causesFirewall
DNS issues
Network connectivity problems
Overloaded server
PHP limits

What Is a 504 Gateway Timeout Error?

The 504 Gateway Timeout Error indicates an issue with your network connection or server communication speed. When the browser sent an HTTP request to the server, it did not receive a response from upstream server in time to complete the request.

504 Bad Gateway Timeout Error Variations and Causes

When you encounter the 504 Bad Gateway error, it will usually look something like this:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

This HTTP error can appear in different forms and various error messages across browsers, servers, and operating systems. Here are the most common ones:

Determining the causes is the first step of fixing the 504 Gateway Timeout error. Here are several problems that may cause 504 gateway timeout:

How to Fix 504 Gateway Timeout Error

In most cases, 504 errors have server-side causes. However, they may also pop up due to issues or an incorrect configuration on the client side.

We’ll go through the basic troubleshooting steps with both options in mind. Most of the solutions apply to any website, but some are WordPress-specific.

1. Refresh the Page

This tip may sound simple, but it’s one of the most common fixes to resolve the 504 gateway timeout error. The server might be receiving more requests than usual, so refreshing the page is worth a try.

The easiest way to do it is to click the Refresh button next to your browser’s address bar or press F5. Alternatively, press Ctrl + F5 to clear the browser cache and force refresh the page.

While waiting for the page to refresh, consider checking if the website is down. Doing so will confirm whether the problem is related to your local network.

2. Check the Order Usage

Each hosting plan allocates a certain amount of resources for optimal website performance. Hostinger users can check their allocated resources by accessing the Order Usage menu from hPanel.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If your WordPress site has reached its hosting plan limits, visitors will see a server error message. If this is the case, contact your hosting provider to upgrade to a hosting plan with more resources to better accommodate your site’s needs.

Another possible solution to this problem is to increase the maximum execution time limit of PHP. Server timeouts can happen when PHP scripts take longer to complete than the defined duration.

Extending the maximum execution time limit will help prevent the scripts from being marked as an error mid-process. Do so by manually editing the .htaccess file, installing the Google Pagespeed Insights plugin, or changing the PHP configuration via your hosting account’s control panel.

Here are the steps to increase the WordPress max-execution-time value via hPanel:

Don’t set the max-execution-time value to 0 as it would allow PHP scripts to run for an infinite period and consume your server resources.

3. Try a Different Browser

If refreshing the page and increasing the maximum execution time limit of PHP scripts didn’t resolve the 504 gateway timeout error, the issue might be browser-related.

Try loading the WordPress site on another browser and using incognito mode to verify that it’s not a server-side error. Clearing the browser cache before reloading the page will also increase its load time and reduce the probability of server timeouts.

4. Flush DNS

DNS issues can originate on both the server and client sides. Server-side DNS issues generally occur on websites with unresolved IP addresses, while client-side ones are caused by an outdated or corrupted DNS cache, which could result in HTTP error 504.

If the WordPress site was recently moved to a different domain or server, the change might not have finished propagating globally. DNS propagation takes between 24-48 hours to complete, so use a DNS propagation checker to verify whether the process is complete.

To fix client-side DNS issues, try flushing your DNS cache. Like browsers, your operating system maintains a local cache. Flushing DNS will eliminate corrupted and outdated cache files that may be causing errors.

The way of doing it differs depending on your operating system. For instance, the following are the steps to flush the DNS cache on Microsoft Windows:

Important! Flushing DNS cache is particularly beneficial to Google Chrome users, as the browser stores a separate cache from the operating system.

Temporary switching the DNS server to a public one is an excellent way to rule out the possibility of a DNS-related problem. Some of the most popular public DNS servers include Cloudflare 1.1.1.1, Google Public DNS, and Comodo Secure DNS.

5. Test with Different Devices

Try loading the website on a different computer, network connection, or mobile phone. You may also try rebooting the network devices to check if it’s a hardware issue or an internet connection problem.

If the HTTP 504 error persists on multiple devices, it’s likely a server-side problem.

6. Check the Error Log

Another possible cause of the 504 gateway timeout error is code corrupted by recent website changes or updates. In this case, checking the error log will help quickly pinpoint the issue.

Hostinger users can activate the PHP error logging feature on hPanel. Here’s how to do it:

If your hosting provider doesn’t offer PHP error logging by default and you’re using WordPress, you can enable debug mode by adding the following lines to the wp-config.php file:

Setting WP_DEBUG_LOG to true will document any errors in the wp-content/debug.log file. Meanwhile, WP_DEBUG_DISPLAY dictates whether or not debug messages will appear on HTML pages.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

7. Check Plugins

In rare cases, a third-party WordPress plugin may be causing the 504 gateway timeout error. Certain plugins, particularly those related to caching, send requests to the server, thus increasing the workload of PHP workers, which might trigger the issue.

Outdated or incompatible plugins can also cause problems. Temporarily disabling all of them will help you check if there’s a faulty plugin.

Navigate to the wp-content directory and rename the plugins folder, which will disable all of your WordPress plugins. You can do this via your hosting account’s File Manager or an FTP client like FileZilla.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If your site works fine when all the plugins are disabled, the next step is to locate which of them is causing the error 504. Restore the original name of the plugins directory and disable the plugins one by one to pinpoint the source of the issue.

8. Check CDNs

If you’re utilizing a Content Delivery Network (CDN) to serve content faster, it’s worth checking whether it functions properly.

One of the most frequently used CDN solutions is CloudFlare, which also acts as a DDoS mitigation service. While using it, you can encounter two versions of the 504 gateway timeout error.

If the error message mentions CloudFlare, then the issue originates there. You can check the Cloudflare system status to clarify whether the company is aware of any network issues.

In this case, contacting CloudFlare support is the fastest way to solve the problem. Otherwise, disable the CDN entirely and wait until the DNS is fully propagated.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

The following version of the 504 error page indicates the problem stems from the web hosting provider, which you should contact for assistance.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

9. Tweak Server Settings

Web server issues are a common cause of the 504 gateway timeout error on websites powered by VPS hosting services.

If you’re using the Apache web server, the error may be triggered by the execution time limit of PHP scripts.

The HTTP 504 errors are often caused by a proxy connection timeout on websites running on Nginx.

The following 504 error page indicates that the issue is related to an Nginx web server error:

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

In the following sections, we’ll discuss tweaking server settings and increasing specific resource limits to solve the 504 gateway timeout error on both platforms.

Apache

Apache users can increase the default timeout value in the httpd.conf file. Add the following line to the Apache configuration file to increase the default timeout value from 300 seconds to 600 seconds:

The new value will prompt the server to wait longer for the request before timing out.

You can also increase the max_execution_time limit in php.ini for PHP scripts to run longer:

After saving the changes, restart Apache. The HTTP 504 gateway timeout error should be gone if it was caused by an insufficient request timeout limit.

Nginx

If your VPS utilizes the Nginx server as a reverse proxy for Apache, try increasing the following values in /etc/nginx/conf.d/timeout.conf:

If you use Nginx with the FastCGI Process Manager (PHP-FPM), you will need to edit the PHP-FPM file. Navigate to /etc/php5/fpm/pool.d/www.conf and add the following line:

We also recommend increasing the max_execution_time in php.ini:

Important! Keep in mind that the location of the configuration file varies based on the installation.

Save the changes, restart Nginx, and reload the website.

10. Contact Customer Support

If the 504 gateway timeout error persists after following all of the above suggestions, it’s best to contact the support team of your web host. Describe what you did during the troubleshooting and provide as much information as possible to speed up the process.

Hostinger users can reach out to our Customer Success team via email or live chat. The latter is accessible from the bottom right corner of the hPanel dashboard page.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Troubleshooting Other 5xx Errors

Conclusion

The 504 gateway timeout error is one of the most common HTTP response status codes that internet users encounter. Even though the error message contains limited information on the source of the issue, there are several different methods to troubleshoot the problem.

Here’s a recap of the ten possible solutions on how to fix the 504 gateway timeout errors:

We hope this article has helped you resolve the HTTP 504 gateway timeout error. If you have any questions or suggestions on how to deal with this issue, leave a comment below.

504 gateway timeout: how to solve the error

Sometimes trying to get access to a web page does not go as planned. You have probably come across the 504 gateway time-out error and wondered what is behind this error message.

In this article, we are going to delve into what the 504 gateway time-out means and what causes it. After looking at the different causes that can generate the error we are going to see the possible solutions.

There are several ways to solve the 504 error and only some of them can be implemented by all users. But what if it’s your site that has problems? Don’t worry, in this guide, we will look exactly into the following: 504 gateway timeout: how to solve the error.

Table of Contents

504 gateway time-out: the meaning of the error

The 504 gateway time-out is an error that is part of the HTTP status codes. This type of error tells us what is going on and allows us to understand what interrupted the loading of the page.

This error is part of the HTTP 5xx Server Error status codes which results in a server error. This type of error occurs when the server fails to complete a request, even though it is valid.

It must be distinguished, therefore, from 4xx Client Error that involves, instead, requests with syntax errors, or requests that cannot be fulfilled. For example, errors 403 and 404.

But let’s focus on server-side errors. These include error 502 bad gateway which occurs when the server acting as a gateway (or proxy) receives an invalid response.

The category of server-side errors also includes 508 error. In this case, it is a warning that informs you that the account resource limits have been exceeded.

What about error 504 gateway time-out?

In this case, too, the server acting as a gateway is involved, but in this case, it fails to receive a response within a time limit. This error can come in different forms because it depends on the settings used by the website.

The error can show up as you see in this screenshot, or in a slightly different form.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

For example, if you are using Cloudflare’s services and you come across this error, you will be faced with a custom screen that always indicates the same error code.

Usually, the most common forms used to indicate this error are:

In each of these cases, the problem is always due to the lack of a response from the server in the maximum time.

But what causes the 504 gateway time-out error?

504 gateway time-out: the causes of the error

As you have seen, an error of this type is encountered when there is a communication failure between an intermediary server and a main server. When too much time elapses before the request is completed, the time limit is exceeded and communication stops.

The problem then occurs for a variety of reasons. It may be that the server is overloaded, not working properly or temporarily out of service.

The error message does not give us any further information about the specific causes. Therefore, often the only way to find the cause of the error is to try to solve it by excluding the causes one by one.

Before we see how to do that, let’s look specifically at what events can cause the error.

Most common problems that generate the error

As we have already mentioned behind the error 504 gateway time-out there can be server errors.

In many cases, it is the infrastructure itself that generates the error. For example, the server may be overloaded. This happens especially when the number of users trying to access the site grows suddenly or in a short time interval.

In such cases, the resources available to the server acting as a proxy will not be necessary to ensure a prompt response to all requests. You may want to consider changing your hosting plan to one that offers more resources or consider changing your hosting. If you choose our shared hosting you can switch to a plan with more resources at any time.

In other cases, however, the overload may be due to DDoS attacks that generate a high number of requests causing the error.

You may also run into the same problem when the resource request comes from a plugin or theme you have installed on WordPress.

A database error can also be responsible for the 504 error on WordPress.

Sometimes the cause of the error is justified, for example, if you are running a script that needs more time to complete its functions. In such cases, you may need to change the settings so that the script can run even if it needs more time to do so.

504 gateway time-out: how to solve it

Since we don’t know the exact cause of this error, the only way to approach it is by exclusion, examining all possibilities one by one.

Since it is an error that involves the server, it is unlikely to be due to the user. However, there are some steps you can take to eliminate any doubt. Let’s start, then, by looking at the user-side solutions.

504 gateway time-out: how to solve it: solutions for users

Let’s see what you can do if the site you’re trying to visit has the 504 gateway time-out error.

Reload the page

As it applies to other errors, the first attempt you can make is always to wait for a while and then reload the page.

Regardless of the browser, you are using you can use the F5 key to do this on Windows and Command + R on Mac.

Restart modem and/or router

Sometimes network errors can be due to the modem or router you use to connect to the network. In these cases, you just need to restart the devices to see if the problem is resolved.

Verify the proxy

If you are using a proxy and some of the settings are wrong, you may encounter errors that prevent you from reaching web pages. Try disabling the proxy and reconnecting to the page.

Change DNS servers

A failure of DNS servers to resolve addresses can result in a 504 gateway time-out. In this case, you can try changing DNS servers from your provider’s to public DNS. You can use Google or Cloudflare DNS for example.

If you don’t know how to do that you can check the step-by-step procedure on how to manually set up DNS servers on Windows 10 and from smartphones with Android.

Contact provider

If all the attempts you have made so far have failed, it means that the http 504 error is not your fault. In this case, you can simply wait and reconnect to the page at a later time. Or you can report the presence of the error to the website operators.

504 gateway time-out: how to solve it: solutions for website owners

If you encounter the 504 gateway time-out error while trying to access your website you have several options to try to resolve it.

Check the errors log

An immediate way to identify error causes on your WordPress site is to go check the error logs.

If your host uses cPanel you can view the errors from the Metrics panel by clicking on Errors, as you see in this screenshot.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

If you can’t access the error logs directly from the control panel you can also use the WordPress debug mode. To do so you just need to edit the wp-config.php file by adding this code:

By doing so, the debug mode will be activated and a file called debug.log will be created in which the recorded errors will be stored.

The file will be saved in the wp-content folder so you only need to access the folder and open it to be able to see it. You can always use the cPanel file manager or the control panel used by your hosting.

Disable CDN

In case you are using a CDN (Content Delivery Network) the problem may come from the CDN servers. In this case you can try temporarily disable the CDN.

Verify themes and plugins

Among the causes of 504 gateway time-out error on WordPress some times the real culprits can be third-party applications.

In some cases disabling WordPress plugins one by one can help us identify which of them is causing the error. The same procedure applies to WordPress themes as well..

There are several ways to disable plugins on WordPress. If you can’t access the dashboard, you can just log in via FTP to the server or use the file manager from cPanel.

In both cases the folder we are interested in is called plugins and you will find it in /public_html/wp-content/. To deactivate all plugins on the site, simply rename the plugins folder to another name.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

This way you will understand if the error is due to one of the plugins you are using.

Increase timeout limits and script execution time

As we saw earlier, another cause of the error can be a PHP script. Some scripts need a longer execution time in order to run. Especially those used for site maintenance or when it comes to importing a large amount of data.

In this case, to solve the 504 gateway time-out error, all you need to do is to change the settings in the php.ini file. The value you will have to change is the maximum execution time, that is:

The default setting is 30 seconds, but depending on your needs you can change the value to allow more time.

You can also change the timeout limit, i.e. the maximum time within which requests must be executed before generating a timeout error.

With Apache, you can do that by modifying the settings of the HTTP server configuration file httpd.conf. The value you have to change is the one next to TimeOut.

With Nginx you have to change the timeout settings from the configuration file, usually nginx.conf. I don’t specify the path to the configuration file because it varies depending on your installation.

The values to modify are those related to timeout, so you’ll find proxy_read_timeout, proxy_connect_timeout, proxy_send_timeout and send_timeout. If these directives are not present you can always add them yourself in this way:

By doing so the timeout will be set to 300 seconds, but of course you can set the value you prefer according to your needs. After you’re done you’ll have to restart nginx for the changes to take effect.

Contact Support

If you were not able to solve the problem on your own, you can contact the customer support of your hosting. If you are our customer you can open a ticket and receive dedicated support with a quick service via the phone or email.

Conclusion

In this article, we have seen the causes of 504 gateway time-out error. After looking at the common issues that can trigger the error we then focused on resolving it.

We’ve seen what you can do if you’re trying to access someone else’s site, and what checks to make in case the problem affects your own site.

Did you manage to solve the problem by following our guide or do you still have doubts? Let me know in the comments below.

Search the blog

Categories

Recent articles

Free Trial

Try our shared hosting for 14 days for free and without obligation. If you’re happy with it, you can upgrade to a paid plan without losing the work you’ve done!

Request failed with status code 504 сбербанк

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504
Другими словами, ошибка 504 указывает на то, что у сервера, на котором расположен сайт и у компьютера, на котором выскакивает ошибка 504, отсутствует стабильное достаточно быстрое соединение с интернетом.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Наверняка многие пользователи Интернета и компьютерных сетей не один раз сталкивались с такой неприятной ситуацией, как появление в браузере кода 504 (ошибка). Не все достаточно четко представляют себе, почему происходит такой сбой и как все это исправить. Давайте посмотрим, что к чему.

Что означает ошибка «504 Gateway time out»?

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Причины появления ошибки

Теперь, насколько это возможно максимально просто, затронем технический аспект. Итак, у нас появляется ошибка 504. Что значит такое сообщение с точки зрения взаимодействия терминала пользователя и удаленного сервера?

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Следующее объяснение может показаться несколько сложным для восприятия, тем не менее здесь все просто. Дело в том, что такие сбои в основном проявляются при взаимодействии платформ Apache и nginx, когда первая установлена в качестве конечного сервера, а вторая – в качестве средства обработки входящих запросов. Получается, что пользовательский запрос адресуется не напрямую к Apache, а проходит предварительное согласование с nginx, после чего производится отправка на сервер, установленный в качестве бэкэнда.

Понятно, что если nginx вовремя не получает ответа от Apache-сервера, он вместо ожидаемого результата и выдает пользователю сообщение с кодом 504 (ошибка). Впрочем, такие ситуации можно исправить, причем даже самым элементарным способом.

Код 504 (ошибка): как с этим бороться?

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Как правило, это либо кнопка «Обновить», либо использование функциональной клавиши F5. Такое правило действует для всех браузеров без исключения. Возможен, правда, более долгий вариант, когда связь является нестабильной. Очень может быть, что в данном случае придется перезагрузить всю систему или даже маршрутизатор (в частности, при использования доступа в Интернет через Wi-Fi-подключение).

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

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

Проблемы при инсталляции приложений

Однако же и это еще не все. Достаточно часто может появляться ошибка при установке (код 504), когда приложение или программа инсталлируется непосредственно из сети Интернет. В данном случае дистрибутив не скачивается на винчестер, а находится на удаленном сервере, с которого и производится установка.

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

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

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

Заключение

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

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

Если сервер, на котором располагается ваш ресурс, перегружен (это происходит вследствие исчерпывания лимита трафика), он выдает пользователю сообщение: «Ошибка 504 gateway time out». В переводе на русский это означает: «время ответа шлюза вышло, шлюз не отвечает». Возникает ситуация, когда Apache чисто физически не может обработать все http-запросы, и они встают в очередь. Однако проходит лимитное время, и приходит сообщение о том, что запрос не обработан.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Чтобы исправить ситуацию, необходимо оптимизировать ваш сервер. Для этого нужно изменить объем оперативной памяти и количество запросов http (Apache) в сторону их увеличения. Еще один вариант — оптимизировать работоспособность всех скриптов, находящихся на вашем сайте. Данная операция поможет поднять производительность обработки.

Если же вы оплачиваете свой хостинг, то следует сразу же обратиться за помощью в саппорт. Служба поддержки обязана проверить ваш сайт на наличие каких-то неисправностей и при возможности «отремонтировать» его. Не стоит пренебрегать такой возможностью. «Дырок», которые необходимо залатать, может быть больше, чем вы думаете. Некоторые хостинг-провайдеры осуществляют техническую поддержку по телефону. Данный вид помощи очень полезен, если вы в первый раз столкнулись с такими техническими проблемами, как ошибка 504. Благодаря такому саппорту вы сможете научиться устранять их самостоятельно, без посторонней помощи.

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Request failed with status code 504. Смотреть фото Request failed with status code 504. Смотреть картинку Request failed with status code 504. Картинка про Request failed with status code 504. Фото Request failed with status code 504

Вот и все, что хотелось вам рассказать о таком явлении, как ошибка 504. Пускай она встречается вам как можно реже!

Источники:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *