Номер ошибки request failed with status code 504

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

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

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

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

Описания ошибки могут иметь различную форму:

  • 504 Gateway Timeout nginx
  • Gateway Timeout Error
  • HTTP Error 504
  • 504 Gateway Time-out – The server didn’t respond in time
  • HTTP Error 504 – Gateway Timeout

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

Производительный хостинг в подарок при заказе лицензии 1С-Битрикс

Выбирайте надежную CMS с регулярными обновлениями системы и профессиональной поддержкой. А мы подарим вам год хостинга – специально для сайтов на 1С-Битрикс.

Заказать

Что делать посетителю сайта при возникновении ошибки 504 

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

  1. Перезагрузите проблемную страницу или текущий браузер. Если проблема устранилась и не повторяется вновь, особенно при посещении других сайтов, о ней можно просто забыть. При регулярном возникновении однотипных ошибок во время посещения разных ресурсов стоит покопаться в настройках собственного ПО поглубже.
  2. Зайдите на тот же самый сайт, где возникла ошибка сервера 504, используя альтернативный браузер. В случае, когда страница во время тестирования открылась корректно, обновите браузер, в котором случился сбой, до последней версии.
  3. Проверьте, как открываются страницы этого же сайта с другого компьютера или смартфона. Это позволит вам понять, не связано ли появление ошибки 504 с ПО конкретного устройства.
  4. При регулярном появлении HTTP ошибок, в т.ч. с кодом 504, очистите кэш браузера, удалите файлы cookies. Со временем в любом браузере накапливается много «мусора». Произведя очистку, вы поможете программе работать более корректно и даже быстрее.
  5. Произведите сброс настроек роутера или модема, отключив оборудование на некоторое время от сети. Данная операция вряд ли приведет к устранению ошибки 504, но может улучшить качество интернет-соединения. Провайдеры регулярно вносят изменения в настройки собственного софта, обновляют его. Иногда это приводит к конфликту в корректном взаимодействии пользовательского оборудования и серверов оператора. Перезагрузка устройства по питанию в большинстве случаев решает такие проблемы.
  6. Очистите кэш DNS. Данная операция кажется сложной для обычного пользователя, но на деле выполнить ее достаточно легко. Способ очистки зависит от вашей операционной системы, найдите соответствующий мануал в интернете.
  7. Для опытных пользователей подойдет рекомендация временно переключить DNS-сервер на Google Public DNS, что как минимум поможет определить, возник ли ошибочный код состояния HTTP по причине DNS проблемы. 

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

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Решение проблем с появлением ошибки сервера 504 администратором веб-ресурса 

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

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

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

Почти все ошибки с кодом 5хх, возникающие из-за невозможности обработки определенного количества запросов, поступающих на сервер, решаются методом апгрейда железа (использованием высокопроизводительного хостинга) либо оптимизацией работы программного обеспечения. Второй способ зависит от вида движка, на котором создан конкретный сайт. При использовании условно-бесплатных программ (WordPress, OpeneCart и других) все проблемы придется решать на уровне администрирования, с привлечением конкретного веб-программиста, разработавшего данный сайт. Если баги возникают на платных платформах (1С-Битрикс, UMI.CMS, NetCat CMS), напишите об ошибке 504 Gateway Time Out в техподдержку разработчика. Отправить сообщение о проблеме следует и разработчикам платных скриптов, если они установлены на вашем сайте, и вы считаете, что сбои возникают по причине их некорректного исполнения. 

Вот некоторые причины, приводящие к возникновению ошибки 504 Gateway Time Out

  • Резкий скачок нагрузки на сайт вследствие поступления большого количества внешних запросов, вызванного DDoS-атаками или действиями вирусного ПО, пиковым посещением сайта, например, в момент проведения различных акций в интернет-магазине, или единовременной загрузкой на сайт большого объема контента (импорт информации из CSV- или XML-файлов).
  • Некорректная работа скриптов, плагинов и дополнений, конфликтующих как между собой, так и внутри.
  • Превышение лимита доступных ресурсов при использовании виртуального хостинга.

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

Рекомендации по устранению ошибки 504 Gateway Time Out методами администрирования сайта

Ошибка 504 Gateway Time Out может быть вызвана недавними изменениями или обновлениями на сайте. Если после отката к состоянию, предшествующему изменениям, баг исчез, следует найти конкретное действие, повлекшее возникновение ошибки. Для этого необходимо проверить журнал ошибок соответствующей CMS. Пользователи WordPress могут включить журналирование ошибок в файле wp-config.php добавлением следующих строк: 

define( 'wp_debug', true );
define( 'wp_debug_log', true );
define( 'wp_debug_display', false )

Все возникающие варианты ошибок будут записаны в файле wp-contents/debug.log.

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

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

Часто ошибку 504 можно видеть на серверах, где используется VPS-хостинг и установлен Nginx в качестве фронтенда и Apache в качестве бэкенда. Для устранения проблемы в Apache можно увеличить значение timeout по умолчанию в файле httpd.conf:

# Timeout: The number of seconds before receives and sends time out.

Timeout 600

Также увеличить лимит в max_execution_time в php.ini: 

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

Аналогичным образом проблема с появлением ошибки HTTP 504 решается пользователями Nginx. Попробуйте увеличить такие параметры в файле /etc/nginx/conf.d/timeout.conf:

proxy_connect_timeout 600;

proxy_send_timeout 600;

proxy_read_timeout 600;

send_timeout 600;

Также рекомендуется увеличить max_execution_time в php.ini:

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

Более простым решением устранения данной проблемы является использование панели управления сервером.

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

Например, в бесплатной панели управления Vesta Control Panel достаточно внести изменения в раздел «Сервер» и навсегда забыть о возможности возникновения ошибок на сайте.

Ошибка ответа сервера 504 Vesta Control PanelИ далее внести соответствующие изменения.

Ошибка ответа сервера 504 Vesta Control Panel

Изменение php.ini в VestaCP

Аналогичным способом проблема устраняется и при использовании альтернативных панелей управления хостингом – Ajenti, CentOS Web Panel, ISPmanager и других.

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

Заключение

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

Буду благодарен, если вы поделитесь своим опытом в комментариях.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

define( ‘wp_debug’, true );

define( ‘wp_debug_log’, true );

define( ‘wp_debug_display’, false );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Очистка DNS

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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.

A 504 Gateway Timeout error can appear in any internet browser, on any operating system, and on any device. This means that it’s possible to get the error on your Android or iPhone phone or tablet, in Safari on a Mac, in Chrome on Windows 10 (or 8, or 7, …), etc.

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:

  • 504 Gateway Timeout
  • HTTP 504
  • 504 ERROR
  • Gateway Timeout (504)
  • HTTP Error 504 — Gateway Timeout
  • Gateway Timeout Error

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

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

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

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

    Windows 10 Proxy Settings.

    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.

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

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

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

    How to Talk to Tech Support

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

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

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.

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.

A 504 Gateway Timeout error can appear in any internet browser, on any operating system, and on any device. This means that it’s possible to get the error on your Android or iPhone phone or tablet, in Safari on a Mac, in Chrome on Windows 10 (or 8, or 7, …), etc.

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:

  • 504 Gateway Timeout
  • HTTP 504
  • 504 ERROR
  • Gateway Timeout (504)
  • HTTP Error 504 — Gateway Timeout
  • Gateway Timeout Error

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

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

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

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

    Windows 10 Proxy Settings.

    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.

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

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

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

    How to Talk to Tech Support

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

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

HTTP Error 504 – 504 Gateway Timeout Status Code Explained

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

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

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

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

What Is the HTTP 504 Error?

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

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

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

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

How to Fix the HTTP 504 Error

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

The following solutions are for users visiting websites:

Refresh Your Browser

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

Disconnect and Reconnect Your Network Devices

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

Clear Browser Data and Cookies

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

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

Find Out If Other Users Are Experiencing the Same Problem

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

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

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

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

Contact Your Hosting Provider

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

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

Check for DNS Changes

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

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

Conclusion

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

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

Thank you for reading!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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?

asked May 7, 2017 at 14:01

Cathy Regan's user avatar

I recently experienced this issue on one of my app’s that was making an ambitious call to it’s Firebase Database — it was grabbing a very large record, which took over 60 seconds (the default timeout) to retrieve.

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:

proxy_connect_timeout       240;
proxy_send_timeout          240;
proxy_read_timeout          240;
send_timeout                240;

Run sudo nginx -t to check the syntax, and then sudo service nginx restart.

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!

answered Oct 3, 2018 at 1:06

Allan of Sydney's user avatar

0

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.

answered May 7, 2017 at 14:20

gnasher729's user avatar

gnasher729gnasher729

51k5 gold badges74 silver badges96 bronze badges

1

One way to fix this is, Changing proxy settings to «NO PROXY» in the browser

It works in Firefox browser, Others I don’t know.

Follow the steps:
1. Go to preferences (top right corner 3 lines, search in drop down)

  1. Search for proxy (Ctrl+F)

  2. Go inside the settings

  3. select «NO PROXY» in the choice buttons, below «Configure Proxy Access to the Internet»

  4. refresh web page.

answered Feb 19, 2020 at 12:10

MADHUKAR's user avatar

0

An HTTP 504 Gateway Timeout error is the most common error encountered by website developers. And in many cases, it can become a real pain.

Generally, it’s difficult to find out the reason for a timeout error because the server response has no helpful information about the error cause.

In this article, we’ll find ways to troubleshoot timeout errors and find solutions for them, while giving you a better understanding of timeout errors and their causes.

What is a 504 Timeout error?

To deeply understand what a 504 Gateway Timeout error is let’s first have a look at server and client relationships.

What happens when the client sends an HTTP request to the server? When the server receives the request, it processes it, and–depending on whether the result is successful or unsuccessful–returns a response with the corresponding HTTP status code in the HTTP response headers.

http request and http response

HTTP status codes are a very important part of the conversation between web servers and clients.

You can find the status code in each server response. All HTTP response status codes are separated into five classes or categories. Each status code is a 3-digit number where the first digit defines the class of response, while the last two digits don’t have any classifying or categorizing role. Here is a list of status codes:

  • 1xx informational response – the request was received, and is being processed
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or can’t be fulfilled
  • 5xx server error – the server failed to fulfill an apparently valid request

If the request is processed successfully by the server it’ll return status code 2xx.

For example, the 200 status code indicates that the server understood the request and successfully processed it. A 201 status code indicates that the request was successful and, as a result, the resource has been created.

The 5xx status codes indicate that there are problems with the server. We have a 504 Gateway Timeout error when the server is running as a gateway or a proxy server. This error happens when the server can’t receive a timely response from the upstream server.

If there’s an issue in the server besides a 504 Gateway Timeout error, it often returns one of these status codes:

500 Internal Server Error

A generic error message for an unexpected condition that has no suitable specific message.

501 Not Implemented

The server either doesn’t recognize the request method, or it lacks the ability to fulfill the request.

502 Bad Gateway

The server is acting as a gateway or a proxy and receives an invalid response from the upstream server.

503 Service Unavailable

This code indicates that the server is temporarily unable to process the client’s request because it is overloaded or down for maintenance.

You can come across other 5xx unofficial codes, like 509, 526, 529, 530, 598, etc. The following codes are not specified by any standard.

504 Errors: Appearance

A 504 Gateway Timeout error can appear in different ways. Depending on the operating system, web browser, and device it may have different looks.

Some websites can customize the template of a 504 Gateway Timeout error to make it look more original and less annoying. Here’s a Google example:

Google's 504 error page

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

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

What causes timeout errors?

A 504 error is a server-side error. In other words, the problem is on the server. This error can occur because of networking errors between servers.

But in very rare cases an error can be caused by client-side issues that are connected to your device or your networking device. For example when you’re trying to access a website from your computer and get a timeout error. In this case, there are some tips to solve this error from your end. We’ll go through these tips in the next section.

Client-side troubleshooting strategies

In very rare cases the cause for 504 errors is on your end. Here are very simple ways to fix it.

Reload the page

The first thing that you should do is reload the page and wait for a minute. If the timeout error disappears it means that it was a temporary problem with the actual server or the networking between servers.

Restart network devices

If reloading the page doesn’t give any result, try to restart your device and your network devices such as modem or router. After restarting the devices reload the page. If it works it means that the temporary problem was on your devices. If not try further steps.

Flush DNS cache

The problem can be from your DNS servers. Linux, Windows, and macOS save name resolution information in the form of a DNS cache. You can clear your DNS cache. For flushing cache on Windows, open Windows command prompt and type:

ipconfig /flushdns

In case of success, you have to get the ‘Successfully flushed the DNS resolver Cache’ message.

On macOS you should open the terminal and type

sudo killall -HUP mDNSResponder

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

sudo killall -HUP mDNSResponder; dns cleared successfully

Cleaning a DNS cache on Linux differs from macOS and Windows. Different Linux distributions use different DNS services. Some of them are NSCD (Name Service Caching Daemon), dnsmasq, and BIND (Berkeley Internet Name Domain). Open the terminal and depending on your own Linux distribution DNS server use one of these commands to flush DNS cache on Linux:
For an NSCD DNS cache:

sudo /etc/init.d/nscd restart

For a dnsmasq DNS cache:

sudo /etc/init.d/dnsmasq restart

For a BIND DNS cache:

sudo /etc/init.d/named restart
sudo rndc restart
sudo rndc exec

If the terminal asks, enter your password. If this doesn’t help, try the next steps.

Change DNS servers

If cleaning the DNS cache didn’t help then you can change your DNS servers. When you change the DNS servers that your internet-connected device uses, you change your servers, usually assigned by your ISP. You can read this article for more information about changing DNS servers: Change your DNS servers settings.

In case you’re using Cloudflare

Cloudflare returns a 504 error and shows a screen with a 504 error custom template when your origin web server responds with a standard HTTP 504 Gateway Timeout error:

standard http 504 gateway timeout error

This is because something is wrong with your server. You can try to fix it with the steps that we’ve already described if it doesn’t help connect to your hosting provider.

If the 504 error is from Cloudflare, the screen may look like this:

Cloudfare 504 error

If the error doesn’t contain the word “Cloudflare”, it means that the problem comes from the actual server. If the error contains the word “Cloudflare”, contactCloudflare support. The same goes for 502 Bad Gateway errors. More about Cloudflare 5xx errors you can find in this article: Troubleshooting Cloudflare 5XX errors.

Server-side troubleshooting strategies

As mentioned the main reasons for 504 Timeout Errors are server-side issues. This can happen due to a variety of reasons: server-side infrastructure, limited server-side parameters, improper firewall configuration, bots, attacks, heavily working PHP scripts, or WordPress imports.

To find out the reason for 504 Timeout Errors you can check your server logs. By checking access logs you can discover if there are any spams from bots. You can also check error logs for information about issues on your website. With 10Web, you can easily do this by going to Hosting Services > Logs. You can select Access Logs, Error Logs, PHP-FPM Logs from the selection at the top of the page.

access server logs via 10Web

If you have access to your server, you can check server logs. Depending on your web server type (Nginx or Apache) the logs can be in /var/log/nginx or in /var/log/apache2 correspondingly.

Server-side infrastructure

Efficient server-side infrastructure has a huge role in avoiding 504 errors. Many shared hostings don’t provide enough resources for high-traffic websites.

That’s why contrary to shared hostings, we, at10web, provide automated WordPress hosting powered by Google Cloud, allowing us to use Linux containers to isolate the resources provided to you. In other words, the MySQL database is in a separate instance which makes lower load in instances possible; hence, there are less 504 errors. If you face a 504 error write to our customer support and the issue will be solved immediately.

Server-side parameters

The other major reason for a 504 Timeout Error is the number of PHP workers. PHP workers are background processes that are responsible for processing PHP code.

If you have only one PHP worker your site can process only one request at once. But this doesn’t mean that the second request won’t be processed. Instead, the PHP processes will be placed in a queue. Only after processing the first request the PHP processes that are next in line will be processed.

In case all PHP workers are busy and the queue is full, 504 or 502 errors may occur. So it’s very important to understand the exact number of workers that will best serve your needs. Depending on your website type (it can be a simple blog or an eCommerce platform that requires processing non-cached pages) you’ll need a different number of PHP workers. Increasing the number of workers allows your website to serve more concurrent requests.

Improper firewall configuration

Another reason for a 504 Gateway Timeout error can be improper firewall configuration.

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It typically establishes a barrier between a trusted network and an untrusted network.

In some cases, there can be awkward firewall settings that consider safe and valid content malicious and, consequently, cut off traffic which in turn can lead to 504 Timeout Errors. Check your server error logs to find out if your firewall has improper configs.

Bots & attacks

Many requests from bots or DDoS attacks by hackers may lead to performance issues in your website which can be a reason for timeout errors. To avoid this you can use Cloudflare, a market leader in DDoS protection.

3rd-party plugins & theme

Heavily working PHP scripts that are written in a non-optimal way can be the reason for timeout errors.

If you have a 504 Gateway Timeout error and find that everything is ok with your server configuration, check plugins your and the theme of your WordPress website.

Deactivate all plugins and start activating them one by one to find out the guilty ones. If you can’t open your WordPress admin dashboard because of the error but have file access to WordPress installation, just rename the plugins folder in wp-content. This will deactivate all plugins. For your theme, you can temporarily change the theme to WordPress’ default theme to discover the issue.

504 Gateway Timeout errors can occur due to cron jobs that are running on your server doing heavy tasks. For checking which crons are running, you can use the WP Control plugin which allows you to view and control what’s happening in the WP-Cron system. If you have access to wp-cli you can run this command for checking crons:

wp cron event list

The result will be:

wp-cron system to find out if it cases a 504 error

To avoid timeout errors you can configure your wp cron in a way that allows it to run like a real cron. Since wp cron works during the request it has max execution time limitation and, hence, can lead to timeout errors. Read more about this here.

Inefficient database queries can also cause timeout errors. To discover such queries you can use the Query monitor plugin, which is a developer tools panel for WordPress. It enables debugging of database queries, PHP errors, hooks and actions, block editor blocks, enqueued scripts and stylesheets, HTTP API calls, and more.

Another useful tool to find timeout errors is wp profile-command package for wp-cli.This doesn’t come with wp-cli. You have to install it yourself. It gives you profiling information about how long each step of your WordPress website loading process has taken. If you have ssh access to your website, you can easily install it by running this command

wp package install [email protected]:wp-cli/profile-command.git

More info about wp-cli you can find in this article: The Last Guide to WP CLI You’ll Ever Need.

WordPress Imports

The plugins WP All Import or WordPress Importer are widely used by WordPress developers for importing XML, CSV files and images to their websites. If the connection between the server and the client is open for a long time during import it can cause timeout errors.

To solve this problem you can try to import the file by chunk, i.e. by dividing it into smaller files. If you have access to wp-cli you can try this command for importing a file:

wp import example.wordpress.2021-03-23.xml

Server configuration

In this section let’s have a look at specific server-side parameters. Increasing these parameters can help solve 504 timeout issues.

If you want to increase max execution time for your php scripts then change the max_execution_time parameter in your php.ini file

max_execution_time = 300

The default value of max_execution_time is 30 seconds.

If your website is running with an Apache web server you can change the TimeOut directive in the httpd.conf file.

TimeOut seconds

Syntax: 
TimeOut seconds 
Default: TimeOut 300 
Context: server config, virtual host

If your website is running with a standalone Nginx web server with a FastCGI Process Manager (PHP-FPM) you can open /etc/php7.4/fpm/pool.d/www.conf and set

request_terminate_timeout = 300

If you want to increase the time limit for a given site, open the /etc/nginx/sites-available/example.com and increase the fastcgi_read_timeout directive

location ~ .php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.4-wplive.sock;
fastcgi_read_timeout 300; 
}

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

http {
	#...
        fastcgi_read_timeout 300; 
	#...
}

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

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

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

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

After increasing params reload Nginx

sudo service nginx reload

What is ERR_CONNECTION_TIMED_OUT?

ERR_CONNECTION_TIMED_OUT means the server is taking too much time to reply.

This error appears when your website is trying to do more than your server can manage. It’s particularly common on shared hosting where your memory limit is restricted.

To fix this you can clear the browser cache or open the page in incognito/private mode. Try all steps mentioned under the section “Client-side troubleshooting”.

Increase your memory limit in wp-config.php. If you don’t have access to your server you can ask your hosting provider to increase your memory limit for you.

Increase the maximum execution time in your php.ini file as we described above or ask your hosting provider.

Cache implementation

The final step of avoiding timeout errors is using caching on your website.

Caching websites has many benefits. It improves website performance and user experience. And it reduces the load in your hosting server.

With 10Web, you can use our hosting cache, which you can enable by heading to Hosting Services > Tools > Website Caching.

website caching via 10Web to avoid a timeout error

For caching you can use different WordPress caching plugins. The popular ones are WP Rocket which improves loading time and W3 Total Cache which improves the SEO and user experience of your site. <!–More info about caching you can find here.–>

Conclusion

In this article, we explored different ways of troubleshooting and fixing a 504 Gateway Timeout error.

While there’s a variety of reasons for a timeout error, we learned that they’re generally caused by server-side problems.

But, of course, non-optimal PHP scripts and database queries and an appropriate number of PHP workers can also have a huge impact on website performance and consequently cause timeout errors.

That was all for now. Feel free to drop a comment and let us know if we managed to provide a suitable way for you to troubleshoot your timeout error!

Понравилась статья? Поделить с друзьями:
  • Ноготь волнистый как исправить
  • Ниссан ошибка р1564 x trail
  • Ногти как клюв как исправить
  • Номер ошибки request failed with status code 502 вконтакте
  • Новорожденный спит на одной стороне головы как исправить форум