Stuck with Cloudflare error 504? We can help you.
Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.
This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.
It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.
Here at Bobcares, we often fix this error for our customers as a part of our Server Management Services.
Today, let’s see how our Support Engineers fix this Cloudflare error for our customers.
What causes error 504 gateway timeout?
Some of the main causes for the Cloudflare 504 gateway timeout error is given below:
1. Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.
2. 504 error originating from Cloudflare end.
3. The 504 gateway timeout error at Cloudflare due to large uploads
How to fix Cloudflare error 504 gateway timeout
We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.
1. Fix for Receiving 504 from the origin web server
We will ensure the below aspects at the webserver:
1. First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.
2. Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.
3. High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.
4. Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.
2. Fix for 504 error originating from Cloudflare
At times error 504 will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.
However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.
For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:
1. The exact time and timezone when the issue occurred
2. URL that resulted in the HTTP 504 error as a response.
3. Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads
The reason for this is the size of the uploads to the site being too large causing server timeouts.
Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.
This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.
[Still, facing error? We are happy to help you!]
Conclusion
To conclude, we saw some of the common causes for the 504 error. Also, we saw how our Support Engineers troubleshoot and fix Cloudflare 504 gateway timeout error.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Stuck with Cloudflare error 504? Cloudflare error 504 gateway timeout occurs when Cloudflare is unable to establish a connection with the origin web server.
This happens when Cloudflare requests a web page and gets blocked by the site’s web server or firewall or load balancer, resulting in the request timeout.
It can also occur if we change the IP address of the origin web server and did not update the same in the Cloudflare portal.
What causes error 504 gateway timeout?
Some of the main causes for the Cloudflare 504 gateway timeout error is given below:
Receiving 504 from the origin web server is considered as one of the common causes of 504 gateway timeout error.
504 error originating from Cloudflare end.
The 504 gateway timeout error at Cloudflare due to large uploads
How to fix 504 gateway timeout
We will see how our Support engineers troubleshoot and fix Cloudflare 504 gateway timeout error for the above-mentioned causes.
- Fix for Receiving 504 from the origin web server
We will ensure the below aspects at the webserver:
- First we will check whether the IP address is correctly set for the domain in the Cloudflare portal.
- Then we have to ensure that the server firewall is not blocking any connections from Cloudflare. We can whitelist the Cloudflare IP addresses if they are not among the whitelisted IPs on the server.
- High load on the server can also lead to timeout issues and website errors. So we will check whether there are any applications running with high CPU usage, or if any website traffic is there on the webserver.
- Finally we will check if the web-server (httpd, apache, nginx) and Mysql services are properly running in the server by checking their status.
- Fix for 504 error originating from Cloudflare
At times error will be arising from Cloudflare’s end. In this case, Cloudflare will be already aware of the issue and working on it.
However, we will confirm this by checking “https://www.cloudflarestatus.com/.” for the Cloudflare System Status.
For avoiding delays in processing the inquiry request we can provide the following details pro-actively to the Cloudflare Support:
- The exact time and timezone when the issue occurred
- URL that resulted in the HTTP 504 error as a response.
- Fix for 504 Gateway Timeout at Cloudflare Due to Large Uploads
The reason for this is the size of the uploads to the site being too large causing server timeouts.
Cloudflare limits upload file size (per HTTP POST request) to 100 MB for both Free and Pro plans.
This issue can be either on the host’s end or Cloudflare’s end. To find this out we will bypass Cloudflare with the DNS hosts file and try to upload again.
Нет ничего более раздражающего, чем появление белого экрана с ошибкой при обращении к WordPress сайту. Некоторые из распространенных ошибок, с которыми вы могли сталкиваться ранее: белый экран смерти, ошибка установки соединения с базой данных и т.д. Для большинства блогов, а также сайтов, связанных с электронной коммерцией, появление таких ошибок приводит к потере дохода, поскольку посетители сразу покидают такой ресурс, а клиенты не могут совершить покупки. Сегодня мы рассмотрим ошибку 504 Gateway Timeout Error, а также дадим рекомендации по поводу того, как справиться с ней на своем WordPress сайте. Читайте далее о причинах этой ошибки и о том, как предотвратить ее появление.
Содержание
- Почему появляется 504 Gateway Timeout Error?
- Варианты ошибки 504 Gateway Timeout Error
- Попробуйте перезагрузить страницу.
- Отключите параметры прокси.
- Проблемы с DNS.
- Временно отключите CDN
- Проблемы с сервером (проверьте ваш хост)
- Спам, боты и DDoS-атаки
- Проверьте ваши плагины и темы.
- Проверьте логи.
- Параметры Nginx
- Заключение
Почему появляется 504 Gateway Timeout Error?
Перед тем, как мы рассмотрим саму ошибку, важно понять, из-за чего она появляется. Всякий раз, когда вы запускаете свой браузер и посещаете сайт, он передает запрос обратно на сервер, на котором размещен. Затем веб-сервер обрабатывает запрос и отправляет вам запрашиваемые ресурсы вместе с HTTP-заголовком. Этот заголовок содержит один из многочисленных кодов состояния HTTP, который позволяет понять, все ли в порядке или что-то пошло не так. Далеко не все коды состояния плохие. К примеру, код состояния 200 говорит о том, что все в порядке.
Существует много различных кодов ошибок 500 (500, 501, 502, 503, 504 и т.д.), которые имеют разное значение. Они указывают, что запрос был принят, но сервер не смог выполнить его.
В данном случае ошибка 504 означает, что «для сервера, работающего в качестве шлюза, вышло время ожидания ответа от другого сервера». Код возвращается, когда есть два сервера, участвующих в обработке запроса, и время ожидания ответа от второго сервера со стороны первого сервера истекло (RFC 7231, раздел 6.6.5).
Варианты ошибки 504 Gateway Timeout Error
Вследствие многообразия веб-браузеров, операционных систем и серверов ошибка 504 может быть представлена разными способами. Все они, как правило, несут в себе одно и то значение. Ниже приведены некоторые из вариантов, с которыми вы можете столкнуться:
- “504 Gateway Timeout”
- “504 Gateway Timeout NGINX”
- “NGINX 504 Gateway Timeout”
- “Gateway Timeout Error”
- “Error 504”
- “HTTP Error 504”
- “HTTP Error 504 – Gateway Timeout”
- “HTTP 504”
- “504 Error”
- “Gateway Timeout (504)
- “504 Gateway Time-out – The server didn’t respond in time”
Как справиться с ошибкой 504 Gateway Timeout Error
С чего следует начать решение проблем, если вы столкнулись с ошибкой 504 Gateway Timeout Error на своем WordPress сайте? Не имея контекста, достаточно сложно понять, что делать в первую очередь. Как правило, ошибку вызывают проблемы с сетевым подключением и проблемы с сервером, на котором расположен сайт. Однако ошибка может быть следствием проблем на стороне клиента или даже результатом использования стороннего плагина. Мы немного углубимся в этот вопрос. Давайте ознакомимся с популярными причинами появления ошибки, а также рассмотрим то, как исправить ее.
-
Попробуйте перезагрузить страницу.
Одна из первых вещей, которую вы должны сделать, столкнувшись с ошибкой 504 Gateway Timeout Error – это просто подождать минуту и перезагрузить страницу. Возможно, хостинг или сервер просто перегружен, и сайт быстро вернется в работу. Вы можете также попробовать другой браузер.
Еще одна вещь, которую вы можете сделать – это проверить статус вашего сайта на downforeveryoneorjustme.com. Этот сайт подскажет вам, вышел ли сайт из строя только у вас или же у всех посетителей. Инструмент проверяет код состояния HTTP, который возвращается сервером. Если код отличается от 200, то в таком случае вы увидите указатель Down (т.е. сайт «лежит» для всех).
-
Отключите параметры прокси.
Иногда вы можете столкнуться с ошибкой 504, если вы используете прокси-сервис. Эти случаи являются очень редкими, особенно на стороне клиента. Однако иногда такие настройки могут быть установлены без ведома клиента. В сети есть руководства, посвященные отключению настроек прокси на Windows и Mac.
-
Проблемы с DNS.
Ошибка 504 gateway timeout может быть вызвана проблемами с DNS. Такая ошибка может возникать с двух сторон. На стороне сервера она происходит, к примеру, когда домен не преобразован в корректный IP. Если вы только что перенесли свой сайт WordPress на новый хостинг, то важно дождаться распространения DNS. Обычно это занимает до 24 часов. Все зависит от значения TTL ваших DNS-записей. Вы можете использовать бесплатный инструмент, такой как DNSMap, чтобы проверить, распространились ли ваши DNS по всему миру.
Вторая проблема с DNS связана уже с клиентской стороной. В этом случае вы можете очистить свой локальный DNS кэш. Это похоже на очистку кэша браузера.
В Windows просто откройте командную строку и введите следующее:
ipconfig /flushdns
Вы должны увидеть сообщение «Successfully flushed the DNS resolver Cache».
В macOS введите следующее в терминал:
dscacheutil -flushcache
Примечание: на Mac нет сообщений об успешном завершении.
И, наконец, вы можете временно изменить ваши клиентские DNS-серверы. По умолчанию DNS-серверы автоматически привязываются вашим интернет-провайдером. Вы можете временно сменить их на публичный DNS-сервер, такой как Google. Некоторые предпочитают постоянно использовать публичные DNS Google, поскольку они в некоторых случаях могут быть более надежными.
-
Временно отключите CDN
Также проблема может связана с CDN (сетью доставки контента). Если вы используете стороннего CDN провайдера, вы можете просто временно отключить ваш CDN. К примеру, нам нравится бесплатный плагин CDN Enabler. Если вы используете его, вы можете просто отключить плагин, чтобы проверить работу сайта. Перестали попадать в консоль WordPress после этого? В таком случае войдите на сайт через SFTP и переименуйте папку с плагином в cdn-enabler_old. В итоге ваше CDN соединение будет временно отключено. То же самое касается плагина WP Rocket или любого другого плагина, который подцеплялся к CDN.
Иногда эта ошибка может быть следствием использования прокси-сервисов, таких как Cloudflare или Sucuri, поскольку у них есть дополнительные файрволы. Большинство из них кэшируют коды состояния 500, когда они возвращаются вашим исходным сервером. Мы заметили, что это время от времени происходит на бесплатном тарифе Cloudflare. К сожалению, поскольку Cloudflare является полным прокси-сервисом, быстрого способа его отключения не существует.
Однако, прежде чем грешить на Cloudflare, важно знать, что есть два типа ошибки 504:
504 Gateway Timeout в Cloudflare (вариант 1)
Если вы видите следующую страницу, то в данном случае проблема на стороне Cloudflare. Обратитесь к ним в поддержку. Либо проверьте их страницу со статусом. Скорее всего, они уже уведомлены о данной проблеме и работают над ней.
504 Gateway Timeout в Cloudflare (вариант 2)
Если вы видите следующую страницу, то это проблема с вашим хостом WordPress (исходный сервер), и в этом случае вам нужно воспользоваться рекомендацией под номером 5.
-
Проблемы с сервером (проверьте ваш хост)
Проблемы с сервером – одна из распространенных причин, почему пользователи сталкиваются с ошибками 504 на своих WordPress-сайтах. Говоря простым языком, Nginx или Apache ожидают ответа от второй стороны, и время ожидания истекло.
Ошибки 504 чаще всего встречаются на сайтах с высоким трафиком и на сайтах электронной коммерции (с установленным WooCommerce, к примеру), у которых много некэшируемых запросов. Это может вызывать перегрузку сервера. Однако мы сталкивались с такими ошибками на разных типах сайтов, в том числе и на обычных блогах. Многие хостинги отвечают стандартными фразами по типу «вам нужно перейти на более дорогостоящий тарифный план, чтобы исправить эту проблему». И пусть это обычно помогает решить данную проблему, зачастую это не является необходимым.
Хостинги, такие как, к примеру, Kinsta, используют контейнеры LXD для каждого сайта. Это означает, что каждый сайт размещается в своем изолированном контейнере, в котором имеются все необходимые программные ресурсы, требуемые для его запуска (Linux, Nginx, PHP, MySQL). Ресурсы на 100% конфиденциальны и не делятся ни с кем. Многие виртуальные хостинги WordPress не имеют данной возможности, поэтому любой соседний сайт с высоким трафиком будет вызывать ошибки 504 на вашем сайте.
В Kinsta инфраструктура построена так, чтобы легко обрабатывать тысячи одновременных подключений. Даже базы данных MySQL размещаются на локальном хосте, а не на удаленном сервере. Это гарантирует отсутствие задержки между машинами, что приводит к более быстрым запросам и меньшей вероятности возникновения тайм-аута между ними.
Помимо тайм-аутов сервера из-за повышенной нагрузки есть и другие причины, в результате чего может возникнуть ошибка 504:
- Медленный сервер. Вполне возможно, что сервер, на котором расположен ваш WordPress сайт, слишком медленно отвечает на запросы, и поэтому он генерирует ошибки шлюза.
- Недостаточно PHP воркеров. PHP-воркеры используются для выполнения кода на вашем WordPress-сайте. На требовательных в плане ресурсов сайтах вполне может быть так, что все PHP-воркеры заняты, и в этом случае они начинают формировать очередь. Если очередь и бэклог заполнены, старые запросы начинают игнорироваться. Вы можете попросить ваш хостинг увеличить количество PHP-воркеров. Дополнительные PHP-воркеры для сайта позволяют одновременно выполнять несколько запросов.
- Проблемы с файрволом. Файрвол на вашем сервере может содержать ошибки в результате неверной конфигурации или правил, препятствующих установлению соединения.
- Сетевое подключение. Если возникают проблемы с сетевым подключением между прокси-сервером и веб-сервером, то это может вести к задержкам с ответом для HTTP-запросов. Также могут возникать сетевые проблемы с балансировщиком нагрузки, если он используется.
Также важно отметить, что ошибки 504 могут обманчиво выглядеть как ошибки 503 (сервис недоступен) или даже ошибки 502 (bad gateway), но на практике они отличаются.
Если вы хотите предотвратить появление таких ошибок в будущем, вы можете воспользоваться инструментом, таким как updown.io, для отслеживания ситуации и немедленного уведомления о любых проблемах. Сервис периодически отправляет HTTP HEAD-запрос к указанному URL. Вы можете просто задать вашу главную страницу. Можно задавать частоту проверок:
- 15 сек
- 30 сек
- 1 мин
- 2 мин
- 5 мин
- 10 мин
Он пришлет вам электронное письмо, если ваш сайт перестал работать, с указанием времени, когда это случилось. Ниже приведен пример:
Это может быть особенно полезно, если вы используете виртуальный хостинг, который, как правило, работает на пределе возможностей. Это даст вам доказательство того, что ваш сайт не работал (к примеру, ночью). По этой причине мы и советуем переходить к администрируемым (управляемым) хостингам.
-
Спам, боты и 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, чтобы включить логгинг:
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false );
Логи обычно расположены в каталоге /wp-content. Иногда они могут находиться в отдельных папках.
Вы можете также проверить логи в Apache и Nginx, которые чаще всего находятся по адресу:
Apache: /var/log/apache2/error.log
Nginx: /var/log/nginx/error.log
-
Параметры Nginx
Если вы обслуживаете свой собственный сервер и WordPress сайты на Nginx + FastCGI (php-fpm) или Nginx как прокси для Apache, то в таком случае есть дополнительные настройки, которые вы можете изменить, чтобы предотвратить появление ошибок 504 gateway timeout.
Если вы используете Nginx с FastCGI (php-fpm), то в таком случае вам нужно сначала внести изменения в файл PHP-FPM. Перейдите в /etc/php5/fpm/pool.d/www.conf (может варьироваться в зависимости от версии PHP). Установите следующую директиву:
request_terminate_timeout = 300
Затем вы должны изменить файл php.ini, который обычно расположен по адресу /etc/php.ini. Найдите директиву max_execution_time. Увеличьте ее значение до 300 или создайте директиву, если ее нет:
max_execution_time = 300
Наконец, вам нужно будет изменить файл nginx.conf. Добавьте в конфигурацию вашего виртуального хоста Nginx следующее:
location ~ .php$ {
...
fastcgi_read_timeout 300;
}
Затем просто перезапустите Nginx и PHP-FPM.
service nginx reload service php5-fpm reload
Если вы используете Nginx в качестве прокси для Apache, то в таком случае добавьте следующее в ваш файл nginx.conf:
proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600;
Далее просто перезапустите Nginx.
service nginx reload
Заключение
Как вы можете видеть, есть много разных способов и методов устранения ошибок 504 gateway timeout на WordPress сайте. Как правило, это проблемы с сервером, и в данном случае вам нужно связаться с вашим хостингом, чтобы решить их. Но важно помнить о том, что они могут также вызываться и сторонними плагинами или переполнением очереди/бэклога ваших PHP-воркеров.
Источник: kinsta.com
If you’ve ever visited a website that serves you on an error page, you would have experienced how frustrating it is classified as the most frustrating thing you can do as a brand doesn’t meet your target audience’s needs and expectations. If you’re a website visitor, you would have probably viewed an error page when the users are looking for help or information. They couldn’t get frustrated and lose trust in your brand, permanently damaging your reputation.
The 504 Gateway Timeout Error is considered one type of error that can hurt the usability experience in such a manner. It will help you avoid the loss of brand sentiments and customer trust. We’ve discussed which type of error it means and the common causes and solutions to improve your website with effective technical SEO. You need to start by conducting this activity. In other words, 504 errors indicate a different computer, the one that your website is getting the message on doesn’t control. Still, it heavily relies on and isn’t communicating with it in a fast-paced environment.
What is a 504 Gateway Timeout Error?
A 504 Gateway Timeout Error can be highlighted in the internet browser window, similar to normal web pages. The 504 error highlights a problem with your network connection or server communication speed.
When the browser sends an HTTP request to the server, it doesn’t receive a response from the upstream server in time to complete the request. Thus the request is “timed out.” Since a 504 Gateway Timeout Error is rather considered a generic format, it doesn’t actually pinpoint the exact cause of the problem. If this happens, your website will serve an error web page to your site’s visitors.
How You Might See the 504 Error?
If you are looking into individual websites are allowed to customize how they show a “gateway timeout” errors, but here are the most common ways that you’ll see one spelled out error:
- 504 Gateway Terminal
- HTTP 504
- 504 ERROR
- Gateway Timeout (504)
- HTTP Error 504 – Gateway Timeout
- Gateway Timeout Error
A 504 Gateway Timeout error is displayed in the internet browser window, similar to what the normal web pages do. There would be a website’s familiar headers and footers, and it seems to be a very nice English message on the page, or it could show up on an all-white page with a big 504 at the top. It shows an instinctive and identical same message, regardless of how the website happens to show it.
What are the Causes of 504 Gateway Timeout Errors
Most of the time, the question arises what does 504 gateway timeout errors mean, it refers to whatever other server is taking so long that its “timing out” is probably down or not working properly. Since this error is based on a network error between servers on the internet or an issue with an actual server, the problem is probably with your computer, device, or internet connection. Hence, there are certain things that you can try in the case of fixing the HTTP 504 gateway timeout error.
How Do I Fix the Fix the 504 Gateway Timeout Error?
If you see a 504 Gateway timeout error, you might be confused about what to do further? You can always try the following steps:
1. Try to Reload the Page
The foremost thing you should do when you face the HTTP Error 504 Gateway Timeout is to simply wait for a minute and reload the page. Regardless, the hosting or server merely is overloaded, and the site will quickly return to work.
In another instance, you can easily check your website status on a specific website. This site will inform you if the site is out of service only for you or for all the visitors. The tools easily check the HTTP status code that is returned by the server. If the code differs from 200, then, in this case, you will see the done pointer. It will mean that the site doesn’t work for everyone.
2. Try a Different Browser
In such a case, the site is online, but you still see the HTTP Error 504 Gateway Timeout. You need to try changing your browser to another one. You must clear the browser cache or use the incognito mode, this can also help the user to determine if the error is caused by the browser.
3. Check on Different Devices
Try opening the site on different computers, on different networks, or on mobile devices. If nothing could help to fix the Error 504 gateway timeout, this step will help you to determine if the problem is on the server-side or it is local.
4. Disable the Proxy
Sometimes you might receive an HTTP 504 error code if you use a proxy server. These cases are quite rare, especially on the client-side. You need to read the guidelines on how to disable proxy on Windows and Mac.
5. Check DNS Records Propagation
Sometimes, HTTP Error 504 gateway timeout often causes a few problems with the DNS server. There are two reasons for that on the server side, it happens whenever the domain name isn’t changed to the correct IP address. If you’ve shifted the WordPress website to a new hosting domain, it’s essential to wait until the address will be implemented to the DNS base. In certain cases, it covers upto 24 hours. It merely depends on your DNS records TTL value.
Also, you can use a freemium tool such as DNSMap to check whether your DNS has been spread across the world. The second DNS issue relates to the client-side, in this case, you can clear your local DNS cache. This is similar to clearing the browsing cache.
In Windows, you need to simply open a command line and type the following instances

Also you should see the “Successfully flushed the DNS Resolver Cache” message.
Using the MacOS, type the following in the terminal:
- dscacheutil -flushcache
Note: there aren’t any messages of successful functions on Mac.
Ultimately, you can temporarily change your client’s DNS servers. By default, DNS servers are provided by your Internet Service Provider. Also it enables users to temporarily change them to a public DNS server, for example provided by Google. There are certain people who usually prefer to use Google’s public DNS constantly because in certain cases that is more reliable and versatile to proceed ahead. Some people prefer to use Google’s public DNS constantly because in certain cases they are more reliable.
6. Temporarily Disable the CDN
Also, the problem that you might relate to the content delivery network, if you use a third-party CDN provider, you can try to temporarily disable it. For that purpose, you may use WordPress plugins, with them you will be able to disable the CDN safely. If you use the backproxy services such as Cloudflare or Sucuri, they may cause the 504 gateway timeout error as they use the extra firewall.
Mostly cache 500 state codes when they are returned by your source server, as users tend to notice the issue on Cloudflare’s freemium plan. Significantly, Cloudflare is a complete proxy service that provides you the fastest way to disconnect it. Although, before blaming cloudflare, it is essential to know that there are two type of 504 gateway timeout errors:
7. 504 Gateway Timeout in Cloudflare (Version 1)
If you see a similar page like this, then in this case, the problem is on the Cloudflare side. You can contact their user support or check their status page. More particularly, they have already been notified about this problem and are working on it.
8. 504 Gateway Timeout in Cloudflare (version 2)
If you see the page appearance like the above one, then this is an issue with your WordPress hosting provider. Users can follow the recommendations in the next step.
Identify the Problems with your Hosting Provider:
The servers encounter certain problems that are one of the common reasons as to why the users experience 504 errors on their WordPress website. In simple terminology, Nginx or Apache waits for a significant response until the waiting time has expired.
504 errors are classified as one of the popular onsites with a lot of visitors, online sites, and online stores. The latter may have installed popular eCommerce plugins such as WooCommerce. They would have many non-cached requests that can cause the servers to overlead.
Although, such errors can happen to a variety of website categories that includes blogs and vice versa. Most of the hosters usually offer to upgrade to a more expensive tariff plan to sort out this problem, and even if this usually assists you to solve this issue, it is often not necessary and essential to proceed ahead.
Conclusion
Certainly, there are a variety of ways and methods to fix HTTP 504 gateway timeout errors on the WordPress site. Typically, this is an issue with the server, and in such circumstances, you need to contact your hosting provider to solve them. But it is essential to remember that they can also be caused via third-party plugins on the queue or backlog overflow for your web developers. Hence, you can know more about HTTP Status Codes via reading online.
An HTTP 504 Gateway Timeout error is the most common error encountered by website developers. And in many cases, it can become a real pain.
Generally, it’s difficult to find out the reason for a timeout error because the server response has no helpful information about the error cause.
In this article, we’ll find ways to troubleshoot timeout errors and find solutions for them, while giving you a better understanding of timeout errors and their causes.
What is a 504 Timeout error?
To deeply understand what a 504 Gateway Timeout error is let’s first have a look at server and client relationships.
What happens when the client sends an HTTP request to the server? When the server receives the request, it processes it, and–depending on whether the result is successful or unsuccessful–returns a response with the corresponding HTTP status code in the HTTP response headers.
HTTP status codes are a very important part of the conversation between web servers and clients.
You can find the status code in each server response. All HTTP response status codes are separated into five classes or categories. Each status code is a 3-digit number where the first digit defines the class of response, while the last two digits don’t have any classifying or categorizing role. Here is a list of status codes:
- 1xx informational response – the request was received, and is being processed
- 2xx successful – the request was successfully received, understood, and accepted
- 3xx redirection – further action needs to be taken in order to complete the request
- 4xx client error – the request contains bad syntax or can’t be fulfilled
- 5xx server error – the server failed to fulfill an apparently valid request
If the request is processed successfully by the server it’ll return status code 2xx.
For example, the 200 status code indicates that the server understood the request and successfully processed it. A 201 status code indicates that the request was successful and, as a result, the resource has been created.
The 5xx status codes indicate that there are problems with the server. We have a 504 Gateway Timeout error when the server is running as a gateway or a proxy server. This error happens when the server can’t receive a timely response from the upstream server.
If there’s an issue in the server besides a 504 Gateway Timeout error, it often returns one of these status codes:
500 Internal Server Error
A generic error message for an unexpected condition that has no suitable specific message.
501 Not Implemented
The server either doesn’t recognize the request method, or it lacks the ability to fulfill the request.
502 Bad Gateway
The server is acting as a gateway or a proxy and receives an invalid response from the upstream server.
503 Service Unavailable
This code indicates that the server is temporarily unable to process the client’s request because it is overloaded or down for maintenance.
You can come across other 5xx unofficial codes, like 509, 526, 529, 530, 598, etc. The following codes are not specified by any standard.
504 Errors: Appearance
A 504 Gateway Timeout error can appear in different ways. Depending on the operating system, web browser, and device it may have different looks.
Some websites can customize the template of a 504 Gateway Timeout error to make it look more original and less annoying. Here’s a Google example:
Different platforms can change the timeout error message. So you can come across different timeout messages but they all have the same meaning.
- 504 Error
- Gateway Timeout (504)
- HTTP 504
- 504 Gateway Timeout
- Gateway Timeout Error
- HTTP Error 504 – Gateway Timeout
- Error 504 Gateway Timeout
What causes timeout errors?
A 504 error is a server-side error. In other words, the problem is on the server. This error can occur because of networking errors between servers.
But in very rare cases an error can be caused by client-side issues that are connected to your device or your networking device. For example when you’re trying to access a website from your computer and get a timeout error. In this case, there are some tips to solve this error from your end. We’ll go through these tips in the next section.
Client-side troubleshooting strategies
In very rare cases the cause for 504 errors is on your end. Here are very simple ways to fix it.
Reload the page
The first thing that you should do is reload the page and wait for a minute. If the timeout error disappears it means that it was a temporary problem with the actual server or the networking between servers.
Restart network devices
If reloading the page doesn’t give any result, try to restart your device and your network devices such as modem or router. After restarting the devices reload the page. If it works it means that the temporary problem was on your devices. If not try further steps.
Flush DNS cache
The problem can be from your DNS servers. Linux, Windows, and macOS save name resolution information in the form of a DNS cache. You can clear your DNS cache. For flushing cache on Windows, open Windows command prompt and type:
ipconfig /flushdns
In case of success, you have to get the ‘Successfully flushed the DNS resolver Cache’ message.
On macOS you should open the terminal and type
sudo killall -HUP mDNSResponder
There’s no message after processing this command, you can add your own, by running the command in this way
sudo killall -HUP mDNSResponder; dns cleared successfully
Cleaning a DNS cache on Linux differs from macOS and Windows. Different Linux distributions use different DNS services. Some of them are NSCD (Name Service Caching Daemon), dnsmasq, and BIND (Berkeley Internet Name Domain). Open the terminal and depending on your own Linux distribution DNS server use one of these commands to flush DNS cache on Linux:
For an NSCD DNS cache:
sudo /etc/init.d/nscd restart
For a dnsmasq DNS cache:
sudo /etc/init.d/dnsmasq restart
For a BIND DNS cache:
sudo /etc/init.d/named restart
sudo rndc restart
sudo rndc exec
If the terminal asks, enter your password. If this doesn’t help, try the next steps.
Change DNS servers
If cleaning the DNS cache didn’t help then you can change your DNS servers. When you change the DNS servers that your internet-connected device uses, you change your servers, usually assigned by your ISP. You can read this article for more information about changing DNS servers: Change your DNS servers settings.
In case you’re using Cloudflare
Cloudflare returns a 504 error and shows a screen with a 504 error custom template when your origin web server responds with a standard HTTP 504 Gateway Timeout error:
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:
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.
If you have access to your server, you can check server logs. Depending on your web server type (Nginx or Apache) the logs can be in /var/log/nginx or in /var/log/apache2 correspondingly.
Server-side infrastructure
Efficient server-side infrastructure has a huge role in avoiding 504 errors. Many shared hostings don’t provide enough resources for high-traffic websites.
That’s why contrary to shared hostings, we, at10web, provide automated WordPress hosting powered by Google Cloud, allowing us to use Linux containers to isolate the resources provided to you. In other words, the MySQL database is in a separate instance which makes lower load in instances possible; hence, there are less 504 errors. If you face a 504 error write to our customer support and the issue will be solved immediately.
Server-side parameters
The other major reason for a 504 Timeout Error is the number of PHP workers. PHP workers are background processes that are responsible for processing PHP code.
If you have only one PHP worker your site can process only one request at once. But this doesn’t mean that the second request won’t be processed. Instead, the PHP processes will be placed in a queue. Only after processing the first request the PHP processes that are next in line will be processed.
In case all PHP workers are busy and the queue is full, 504 or 502 errors may occur. So it’s very important to understand the exact number of workers that will best serve your needs. Depending on your website type (it can be a simple blog or an eCommerce platform that requires processing non-cached pages) you’ll need a different number of PHP workers. Increasing the number of workers allows your website to serve more concurrent requests.
Improper firewall configuration
Another reason for a 504 Gateway Timeout error can be improper firewall configuration.
A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It typically establishes a barrier between a trusted network and an untrusted network.
In some cases, there can be awkward firewall settings that consider safe and valid content malicious and, consequently, cut off traffic which in turn can lead to 504 Timeout Errors. Check your server error logs to find out if your firewall has improper configs.
Bots & attacks
Many requests from bots or DDoS attacks by hackers may lead to performance issues in your website which can be a reason for timeout errors. To avoid this you can use Cloudflare, a market leader in DDoS protection.
3rd-party plugins & theme
Heavily working PHP scripts that are written in a non-optimal way can be the reason for timeout errors.
If you have a 504 Gateway Timeout error and find that everything is ok with your server configuration, check plugins your and the theme of your WordPress website.
Deactivate all plugins and start activating them one by one to find out the guilty ones. If you can’t open your WordPress admin dashboard because of the error but have file access to WordPress installation, just rename the plugins folder in wp-content. This will deactivate all plugins. For your theme, you can temporarily change the theme to WordPress’ default theme to discover the issue.
504 Gateway Timeout errors can occur due to cron jobs that are running on your server doing heavy tasks. For checking which crons are running, you can use the WP Control plugin which allows you to view and control what’s happening in the WP-Cron system. If you have access to wp-cli you can run this command for checking crons:
wp cron event list
The result will be:
To avoid timeout errors you can configure your wp cron in a way that allows it to run like a real cron. Since wp cron works during the request it has max execution time limitation and, hence, can lead to timeout errors. Read more about this here.
Inefficient database queries can also cause timeout errors. To discover such queries you can use the Query monitor plugin, which is a developer tools panel for WordPress. It enables debugging of database queries, PHP errors, hooks and actions, block editor blocks, enqueued scripts and stylesheets, HTTP API calls, and more.
Another useful tool to find timeout errors is wp profile-command package for wp-cli.This doesn’t come with wp-cli. You have to install it yourself. It gives you profiling information about how long each step of your WordPress website loading process has taken. If you have ssh access to your website, you can easily install it by running this command
wp package install [email protected]:wp-cli/profile-command.git
More info about wp-cli you can find in this article: The Last Guide to WP CLI You’ll Ever Need.
WordPress Imports
The plugins WP All Import or WordPress Importer are widely used by WordPress developers for importing XML, CSV files and images to their websites. If the connection between the server and the client is open for a long time during import it can cause timeout errors.
To solve this problem you can try to import the file by chunk, i.e. by dividing it into smaller files. If you have access to wp-cli you can try this command for importing a file:
wp import example.wordpress.2021-03-23.xml
Server configuration
In this section let’s have a look at specific server-side parameters. Increasing these parameters can help solve 504 timeout issues.
If you want to increase max execution time for your php scripts then change the max_execution_time parameter in your php.ini file
max_execution_time = 300
The default value of max_execution_time is 30 seconds.
If your website is running with an Apache web server you can change the TimeOut directive in the httpd.conf file.
TimeOut seconds
Syntax: TimeOut seconds Default: TimeOut 300 Context: server config, virtual host
If your website is running with a standalone Nginx web server with a FastCGI Process Manager (PHP-FPM) you can open /etc/php7.4/fpm/pool.d/www.conf and set
request_terminate_timeout = 300
If you want to increase the time limit for a given site, open the /etc/nginx/sites-available/example.com and increase the fastcgi_read_timeout directive
location ~ .php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.4-wplive.sock;
fastcgi_read_timeout 300;
}
To increase the time limit for all sites, open the /etc/nginx/nginx.conf file and
http {
#...
fastcgi_read_timeout 300;
#...
}
After changing params don’t forget to reload PHP FPM and Nginx:
sudo service nginx reload sudo service php7.4-fpm reload
If you’re using Nginx as a reverse proxy server for Apache then you have to change these directives in your nginx.conf file:
proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600;
After increasing params reload Nginx
sudo service nginx reload
What is ERR_CONNECTION_TIMED_OUT?
ERR_CONNECTION_TIMED_OUT means the server is taking too much time to reply.
This error appears when your website is trying to do more than your server can manage. It’s particularly common on shared hosting where your memory limit is restricted.
To fix this you can clear the browser cache or open the page in incognito/private mode. Try all steps mentioned under the section “Client-side troubleshooting”.
Increase your memory limit in wp-config.php. If you don’t have access to your server you can ask your hosting provider to increase your memory limit for you.
Increase the maximum execution time in your php.ini file as we described above or ask your hosting provider.
Cache implementation
The final step of avoiding timeout errors is using caching on your website.
Caching websites has many benefits. It improves website performance and user experience. And it reduces the load in your hosting server.
With 10Web, you can use our hosting cache, which you can enable by heading to Hosting Services > Tools > Website Caching.
For caching you can use different WordPress caching plugins. The popular ones are WP Rocket which improves loading time and W3 Total Cache which improves the SEO and user experience of your site. <!–More info about caching you can find here.–>
Conclusion
In this article, we explored different ways of troubleshooting and fixing a 504 Gateway Timeout error.
While there’s a variety of reasons for a timeout error, we learned that they’re generally caused by server-side problems.
But, of course, non-optimal PHP scripts and database queries and an appropriate number of PHP workers can also have a huge impact on website performance and consequently cause timeout errors.
That was all for now. Feel free to drop a comment and let us know if we managed to provide a suitable way for you to troubleshoot your timeout error!
check server related issues
# 1 SSL Configuration
SSL Config with cloudflare if SSL Certificate hosted at sever then SSL Setting in the cloudflare should be strict, not flexible.
flexible if no ssl certificate presented at origin.
#2 Check http header size limit (over 8kb) if it s above cloudflare limits you get this 52o error
tip: also check server logs in origins host.
520 error means
#Temporary Error (502): The server encountered a temporary error and could not complete your request.
#502 Service Temporarily Overloaded
# HTTP Error 502 – Bad Gateway
#Bad Gateway: The proxy server received an invalid response from an upstream /origin server.
1.
#502 Proxy Error
cloudflare timeout error fix 504
to fix this server timeout 300s (5minutes)
php or any backend application (5 minutes equal or less than server timeout)
database mysql timeout is generally 2 hours.
in nginx
fastcgi as a proxy so we can increase timeout,
clients limits (server to user/browser).
NOTE: these timeout errors temporary during peak.
when limited can’t finish the request in specified time.
if you are shared hosting aske them increase limits or ignore, if problem occurs frequently move to another host or upgrade your plan.
move to vps or cloud hosting.
shared host limits
500X problems related servera unlike 404 not found 301 redirect 200 ok
nginx side proxy readtimeout (Fixed)
500 Internal Server Error
503 Service Unavailable
504 Gateway Timeout
520 Web Server Returned an Unknown Error
The origin server returned an empty, unknown, or unexplained response to Cloudflare.[91]
521 Web Server Is Down
Error 521 occurs when the origin web server refuses connections from Cloudflare. Security solutions at your origin may block legitimate connections from certain Cloudflare IP addresses.
522 Connection Timed Out
Error 522 occurs when Cloudflare times out contacting the origin web server.
523 Origin Is Unreachable
Cloudflare could not reach the origin server; for example, if the DNS records for the origin server are incorrect.
524 A Timeout Occurred
Cloudflare was able to complete a TCP connection to the origin server, but did not receive a timely HTTP response.
525 SSL Handshake Failed
Cloudflare could not negotiate a SSL/TLS handshake with the origin server.
526 Invalid SSL Certificate
Cloudflare could not validate the SSL certificate on the origin web server. Also used by Cloud Foundry’s gorouter.
527 Railgun Error
Error 527 indicates an interrupted connection between Cloudflare and the origin server’s Railgun server.[92]
530
Error 530 is returned along with a 1xxx error
500 Internal Server Error
A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
502 Bad Gateway
The server was acting as a gateway or proxy and received an invalid response from the upstream server.
503 Service Unavailable
The server cannot handle the request (because it is overloaded or down for maintenance). Generally, this is a temporary state
504 Gateway Timeout error fic
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. just increase timeout or mitigaate what caused the long delay.
how to fix 504 gateway nginx timeout error?
504 gateway time out problem description.
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.
client_header_timeout 300;
client_body_timeout 300;
fastcgi_read_timeout 300;
client_max_body_size 32m;
fastcgi_buffers 8 128k;
fastcgi_buffer_size 128k;
if still not solved try below
in case of fastcgi
fastcgi_buffers 8 128k;
fastcgi_buffer_size 256k;
fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
how nginx causes 504 timeout?
this error appears mainly nginx installed servers. because nginx reduces max_execution_time for .php script.
how to fix 504 error in nginx servers.
simply we need to increase timeout range unfortunately newbies without knowledge can’ do this we need to contact hosting support for increasing limit. some times it’s not worked hosting providers ask permission you to uninstall nginx. if you do this you are out of 504 gateway error. but you get high cpu load on server.
how to increase the timeout limit in ngnix?
/etc/ngnix/ngnix.conf
send_timeout 120;
proxy_read_timeout 120;
proxy_connect_timeout 120;
If they are not there you may add them or create a .conf file in /etc/nginx/conf.d/ folder with those values.
Then restart nginx:
# /etc/init.d/nginx restart
read more about this ngnix .org official.
to fix 520 521 523 524 gate way time out in cloudflare
these errors not by cloudflare it’s by your web server.
fix nginx 502 bad gateway
open /etc/nginx/nginx.conf
add the following lines into http section :
|
1 2 |
fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; |
you config should look like this :
|
1 2 3 4 5 6 7 8 |
http { . . fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; . . } |
Restart nginx and fastcgi.
How do I fix Cloudflare error 502 bad gateway?
its a temporality problem,
you can read http status codes and their meanings here
resource may help you
http://www.nginxtips.com/502-bad-gateway-using-nginx/
http://www.unixmen.com/how-i-fixed-nginx-502-bad-gateway-error/http://stackoverflow.com/questions/3704626/nginx-502-bad-gateway-error-only-in-firefox




















