Error 504 gateway timeout apache

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

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

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

задан 4 авг 2016 в 13:35

lecherg's user avatar

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

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

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

ответ дан 4 авг 2016 в 13:55

Firepro's user avatar

FireproFirepro

9,2869 серебряных знаков33 бронзовых знака

2

Gateway time-out также может возникать, когда Nginx используется как прокси-сервер. Например, при работе с Apache. Для того, чтобы избежать проблем, необходимо настроить параметры времени ожидания при проксировании:

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

ответ дан 22 июн 2017 в 13:55

Dmitry Maslennikov's user avatar

Dmitry MaslennikovDmitry Maslennikov

4,4174 золотых знака24 серебряных знака47 бронзовых знаков

Ошибка 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 ошибка точно не будет появляться на сайте.

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

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

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

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

Если вы обычный пользователь

  1. Если сервер перегружен, то выдаст ошибку 504 Gateway Time-out. В этом случае вам нужно просто подождать пару минут и перезагрузить страницу кнопкой F5 или Ctrl+F5.
  2. Если вы используете прокси-сервер, то удалите его. Известно, что неправильные настройки прокси, могут выдавать ошибку 504. Особенно это касается бесплатных прокси, которые раньше могли работать нормально, но в будущим дать сбой.
  3. Если у сайта была смена DNS адресов, то вам нужно очистить список локальных DNS на своем компьютере. Для этого запустите командную строку от имени администратора и введите команду: ipconfig /flushdns.

ipconfig /flushdns

Если вы веб-мастер

  1. Обратитесь в поддержку вашего хостинга для выявления проблемы ошибки 504 Gateway Time-out.
  2. Посмотрите нагрузку базы данных своего ресурса.
  3. Посмотрите количество запросов к серверу, это могут быть боты или Ddos атака.
  4. Если вы изменили DNS-адреса, то должно пройти 24 часа минимум для их применения.
  5. Если вы используете CDN как Cloudflare, то этот поставщик контента мог закешировать ошибку. Попробуйте отключить на время и проверить.
  6. Вам нужен более мощный сервер, так как текущий не выдерживает нагрузки пользователей.

Смотрите еще:

  • Как исправить ошибку 502 Bad Gateway в браузере
  • Ошибка HTTP Error 503 The service is unavailable
  • 403 Forbidden — Что это значит и как исправить 
  • Исправить ошибку ERR_TOO_MANY_REDIRECTS в браузере 
  • Исправить ошибку Err_Connection_Closed в браузере

[ Telegram | Поддержать ]

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

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




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

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

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

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

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

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




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

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

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

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

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

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

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


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

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

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




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

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




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

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

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

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

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

sudo killall -HUP mDNSResponder

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

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

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

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

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

1 способ

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

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

2 способ

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

3 способ

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

  1. 1.

  2. 2.

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

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

4 способ

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


Что такое CDN

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

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

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

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

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

1 способ

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

2 способ

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

  1. 1.

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

  2. 2.

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

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

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

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

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

  4. 4.

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

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

  • Ошибка 504 ― что значит
  • Как устранить код ошибки 504 Gateway Time Out владельцу сайта
  • Долго обрабатывается скрипт
  • Проблемы с CDN
  • Выросла нагрузка на один из серверов
  • Проблемы с сайтами на WordPress
  • Что может сделать пользователь

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

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

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

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

  • HTTP Error 504,
  • Gateway Timeout Error,
  • HTTP Error 504 – Gateway Timeout,
  • 504 Gateway Timeout nginx,
  • Ошибка 504 Время ответа сервера истекло,
  • Время ожидания шлюза (504),
  • Ошибка тайм-аута шлюза.

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

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

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

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

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

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

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

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

PHP

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

  1. Откройте файл php.ini.
  2. Добавьте строку:
max_execution_time = 60

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

Nginx

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

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

sudo nano /etc/nginx/nginx.conf

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

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

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

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

service nginx reload

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

Apache

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

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

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

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

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

Проблемы с CDN

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

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

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

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

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

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

  1. Повысился спрос на ваш товар. Это позитивная причина. Возможно, скоро праздники и все закупаются подарками, а ваш продукт пользуется спросом. Также посетителей может привлечь рекламная кампания. Для решения такой проблемы достаточно приобрести тариф хостинга или VPS с большей мощностью. Тогда сервер сможет принять большой поток клиентов.
  2. На вас была сделана DDoS-атака. Ваши недоброжелатели могут искусственно создать большой поток посетителей и вывести сайт из строя. На хостинге и VPS от 2DOMAINS есть встроенная защита от DDoS-атак.
  3. На сервере появился вирус. Вирусы могут нарушать работу сервера, перегружая его. Проверьте ваш сайт на вирусы. Если найдёте, удалите их и проверьте работоспособность сайта. 

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

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

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

  1. Перезагрузите страницу. Если ошибка появилась из-за перегрузки сервера, вы можете подождать и зайти на сайт, когда наплыв посетителей закончится. Если ошибка связана с настройкой сервера, подождите, пока владелец не починит сайт.
  2. Откройте сайт на другом браузере. Неисправные или старые версии браузеров могут показывать разные ошибки, в том числе и 504-ю. Попробуйте открыть веб-ресурс на любом другом браузере. Если сайт заработает, проверьте обновление основного браузера или переустановите его.
  3. Откройте сайт на другом устройстве. Если проблема в самом устройстве, можно попробовать открыть сайт на смартфоне или другом ПК. Если сайт работает, проверьте корректность работы устройства и драйверов.
  4. Перезагрузите сетевые устройства. Временные проблемы с вашим модемом, маршрутизатором или другим сетевым оборудованием могут вызвать проблему 504 Gateway Timeout. Перезагрузка этих устройств может помочь.
  5. Очистите кэш браузера. Если вы часто встречаете разного рода ошибки на сайтах, возможно, проблема в переполненном кэше браузера. Со временем в любом браузере накапливается много «мусора», который нужно удалять. Очистить кеш вам помогут инструкции:
  • Как очистить кэш браузера,
  • Как очистить кэш браузера Safari.

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

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

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

What is the 504 Gateway Timeout Error?

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

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

There are many WordPress error messages that you might have experienced on your website. You can also check out some of the lists of the most common WordPress errors and their solution.

  • The white death screen
  • Error Establishing a Database Connection
  • Too Many Redirect Errors
  • 502 Error Bad gateway

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

  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • Gateway Timeout Error
  • 504 gateway timeout PHP
  • Error 504
  • 504 Error Code
  • 504 Status Code
  • HTTP Error 504
  • Gateway Timeout Error 504
  • HTTP 504
  • 504 Error
  • Gateway Timeout (504)
  • 504 Gateway Time-out – The server didn’t respond in time

What Are The Causes of the 504 Gateway Timeout Error?

Causes of the 504 Gateway Timeout Error
Causes of the HTTP 504 Gateway Timeout Error

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

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

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

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

  • Slow server- It is possible that the server where you host your WordPress website is responding too slowly, and therefore it generates gateway errors.
  • Insufficient PHP workers- PHP workers are used to running code on your WordPress site. Demanding sites can make all PHP workers busy. In that case, they form the queue. If the queue and the backlog are full, old requests are ignored. You can ask your hosting to increase the number of PHP workers. Additional PHP workers for a site allow the execution of several requests simultaneously.
  • Problems with the firewall- The firewall on your server may contain errors due to incorrect configuration or rules blocking the connection.
  • Network connection- If there is a problem with the network connection between the proxy server and the web server, this can lead to delays. Also, there may be network problems with the load balancer, if it is used.
Fixes of the HTTP 504 Gateway Timeout Error
Fixes of the HTTP 504 Gateway Timeout Error

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

  • Try to reload the page
  • Try a different browser
  • Check on different devices
  • Disable the proxy server
  • Check DNS records propagation
  • Temporarily disable the CDN
  • Check the issues with your hosting provider
  • Clean the site from spam, bots and protect it from DDoS attacks
  • Check your plugins and themes
  • Check the logs
  • Change Nginx options

Try to reload the page:

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

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

Try a different browser:

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

Check on different devices:

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

Disable the proxy Server:

Disable the proxy server in Windows PC
Disable the proxy serverin Windows PC

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

For Windows users

Step 1: Go to your chrome browser and click on the menu button “” located at the top right corner and select “Settings”.

Step 2: Now scroll down and select the “system” section followed by “Open Proxy settings“.

Step 3: If you are a Windows 10 user or above it, this will open a separate proxy settings window.

Step 4: In the proxy settings window you will find two sections, Automatic proxy setup, and Manual proxy Setup.

Under Automatic Proxy Setup, Turn off: Automatically detect settings (Toggle button) and Use setup script (click on Set up > Turn off > Save)

Under Manual Proxy Setup, Turn off: Use a Proxy Server (Click on Setup button> Turn off > Save)

Under Manual Proxy Setup, Turn off: Use a Proxy Server (Click on Setup button> Turn off > Save)

For Mac Users, they can do the following steps to disable proxy settings:

Step 1: Go to the Apple menu or click on the apple icon located at the top left of your Mac screen.

Step 2: Click on System settings or System preferences, whichever is applicable.

Step 3: Now click on the “Network” in the sidebar.

Step 4: From the right pane, Select a network service > click the Advanced button.

Step 5: Click on the Proxy tab and mark uncheck all the protocols under “Select a protocol to configure” and click on the “Ok” button when done.

Check DNS records propagation:

DNS propagation check
DNS propagation check

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

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

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

ipconfig / flushdns

Flush DNS in ipconfig
Flush DNS in ipconfig

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

In macOS, type the following in the terminal:

dscacheutil -flushcache

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

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

Temporarily disable the CDN:

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

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

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

504 Gateway Timeout in Cloudflare (version 1)

504 status code
504 status code

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

504 Gateway Timeout in Cloudflare (version 2)

504 Gateway Timeout in Cloudflare
HTTP status 504 error

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

Check the issues with your hosting provider:

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

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

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

Note: HTTP 504 errors may look very similar to 503 errors (service unavailable) or even 502 errors (bad gateway). But actually, they are different, to know more you can also check out our post on “15 Best Methods to Fix 502 Bad Gateway Error“.

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

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

http error code 504
Tracking server state using status cake tracker tool

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

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

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

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

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

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

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

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

Too many 504 Gateway issues
WPOven

Check Your Plugins and Themes:

Many users believe that third-party plugins or themes do not lead to 504 gateway timeout errors. And in most cases this is true. But, according to many users’ experience, a slow non-cached plugin request can cause delays, since it uses more of your PHP workers.

Once you reach the limit of them, the queue will remove your old requests, which can cause HTTP 504 errors. They should not be confused with 502 errors which are the result of a 60 seconds timeout.

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

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

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

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

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

Check the Logs:

You can also use your error logs. One can view them in a special section of the hosting dashboard. You can quickly fix the issue, especially if its source is the website plugin. If your hosting does not offer logging tools, you can add the following code to the wp-config.php file to enable logging:

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

Logs are usually located in the/wp-content folder. Sometimes they can be in separate folders. You can also check the Apache and Nginx logs which are most often located at /var/log/apache2/error.log (Apache) or /var/log/nginx/error.log (Nginx)

Change Nginx Options:

If you are maintaining your server and WordPress website on Nginx+FastCGI (php-fpm). Also, you can use Nginx as a proxy for Apache. In that case, there are additional settings that you can change to prevent 504 gateway timeout errors.

If you are using Nginx with FastCGI (php-fpm), then you need to first make changes to the PHP-FPM file. Go to /etc/php5/fpm/pool.d/www.conf (it can vary depending on the PHP version). Set the following directive:

request_terminate_timeout = 300

Then you must modify the php.ini file, which is usually located at /etc/php.ini. Find the max_execution_time directive. Increase its value to 300 or create a directive if it does not exist:

max_execution_time = 300

Finally, you will need to modify the nginx.conf file. Add the following to your Nginx virtual host configuration:

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

Then just restart Nginx and PHP-FPM.

service nginx reload
service php5-fpm reload

If you use Nginx as a proxy for Apache, then in this case add the following to your nginx.conf file:

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

Next, just restart Nginx.

service nginx reload

Contact Support

If you constantly face an HTTP 504 gateway timeout error and nothing helps to fix it, contact the hosting technical support. Try to describe what steps you have taken to identify the error cause and provide as much information as possible. This will greatly speed up the process.

Conclusion

As you can see, there are many different ways and methods to fix HTTP 504 gateway timeout errors on the WordPress site. Typically, this is a problem with the server, and in this case, you need to contact your hosting to solve them. But it’s important to remember that they can also be caused by third-party plugins or your PHP workers’ queue/backlog overflow. You can know more about HTTP Status Codes via reading online.

Summary

From the above post, you have come across how your WordPress site is quite vulnerable to experiencing 504 Gateway timeout due to various reasons. And in this post, you have also learned multiple working methods to resolve the issue quickly.

Generally, these kinds of errors or issues are generated from the server end itself, and for that, it is highly recommended to contact your web host to fix the issue ASAP.

Apart from server issues, you must also consider that the 504 gateway timeout error can also be triggered due to faulty third-party plugins, themes, databases, etc. In that case, you must check out all the possible reasons and then work on them.

In case, if you find your website is still facing timeout issues and no method worked to fix it. It is highly advisable you must migrate your website to a more reliable and trustful Managed web host.

If we missed anything to mention in this post or if you would like to share your opinions about the 504 Gateway timeout error, feel free to write in the comment section below.


Eliminate the risk of “504 Gateway timeout error” by choosing a more reliable and fastest server. Host or migrate your website on WPOven’s Fully managed dedicated servers and enjoy the best in the industry unmatchable features such as,

  • Fastest Private servers
  • Upto 100% uptime monitoring
  • Antimalware scanning
  • 24X7 WordPress Expert support
  • Cloudflare integration
  • High-end Security
  • Datacentres around the world, etc.

You can have all these features and much more in a single plan with unlimited Free migrations, unlimited staging, and a 14-day risk-free guarantee, Signup Now!

Frequently Asked Questions

What causes a 504 Gateway Timeout?

The possible causes that trigger a 504 Gateway Timeout error are:
1. Slow server speed
2. Insufficient PHP workers
3. Problems with the Firewalls
4. Network Connection

How do I fix a 504 Gateway Timeout?

You can easily fix a 504 Gateway timeout error by following these simple methods:
1. Try to reload the page
2. Try a different browser
3. Check on different devices
4. Disable the proxy
5. Check DNS records propagation
6. Temporarily disable the CDN
7. Check the issues with your hosting provider
8. Clean the site from spam, bots and protect it from DDoS attacks
9. Check your plugins and themes
10. Check the logs
11. Change Nginx options

Is a 504 Gateway Timeout my fault?

The error 504 Gateway timeout happens due to the fault from the server side. Generally, requests sent from the clients are good but due to some issue at the server, sometimes they are unable to generate the requested resource. In simple words, this error simply means that your web server didn’t get any response from another server on time while accessing the webpage.

You may have encountered the 504 Gateway Timeout Error a few times while trying to visit websites.

It can be frustrating as the 504 Gateway Timeout Error is one of the most common errors faced by users and site owners. Unfortunately, it’s also a mysterious error because it doesn’t specify what the issue is.

If you own a website or a blog, it will be helpful to understand what the 504 Gateway Timeout Error is, find out what is causing it, and ultimately fix it.

This article will help explain all you need to know about the 504 Gateway Timeout Error.

Table Of Contents

  • What is the 504 Gateway Timeout Error?
  • Variations of the 504 Gateway Timeout Error
  • Potential Causes of the 504 Gateway Timeout Error
  • How to Fix the 504 Gateway Timeout Error: 5 Ways
    • 1. Reloading Your Website
    • 2. Restart All Network Devices
    • 3. Check The Proxy Server Settings
    • 4. Change DNS Servers
    • 5. Temporarily Disable Your Site’s Content Delivery Network
  • Various Examples of 504 Gateway Timeouts (How the Errors Look/What the Differences Are)
  • Why Are You Seeing The 504 Gateway Timeout Error Message? 
    • 1. Server Issues (Check With Your Host)
    • 2. Firewall Issues 
    • 3. Slow Server Infrastructure 
    • 4. Network Connectivity problems 
    • 5. HTTP Timeouts
    • 6. Needs more PHP Workers 
    • 7. Spam, Bots, or DDoS Attacks 
    • 8. Corrupted WordPress Database
  • Troubleshooting (Health Mode)
  • Check Your Site’s Plugins, Theme, and Server Error Logs
    • 1. Configure Apache or Nginx Settings Properly 
    • 2. 504 Gateway Timeout Error on Nginx + FastCGI (PHP-FHM) 
    • 3. 504 Gateway Timeout Error on Nginx Proxy 
    • 4. Other HTTP Errors Like 504 Gateway Timeout 
  • Conclusion

In simple terms, the 504 gateway timeout error happens when the website doesn’t receive a timely response from a server. Each time you visit a website, the browser will send a request to the server where the site is hosted. The server processes the requests and responds to the website with the requested resources.

The 504 gateway timeout error is mysterious and can be challenging to fix. It indicates the server was unable to process the request, but it doesn’t tell you why it was unable to do so. It also tells you the server is aware it couldn’t carry out the request but was unable to fix the issue in time.

Variations of the 504 Gateway Timeout Error

Depending on your operating system and browser, the 504 gateway timeout error can appear in various ways.

Some of the common 504 error messages may look like this:

  • HTTP 504
  • HTTP Error 504
  • 504 Gateway Timeout
  • The page isn’t working – Domain took too long to respond

Your browser and certain websites can customize how the error message is displayed. Though the message can be worded in different ways, it points to the same server error.

Potential Causes of the 504 Gateway Timeout Error

So, what could cause the 504 gateway timeout error? Since the error refers to the server timing out on a request, it usually points to an issue with the network rather than with the device.

server overheating causing 504 gateway timeout error

Some of the possible causes could be:

  • Server is currently not working or under maintenance
  • Server is not functioning properly
  • Connection between server and internet was interrupted
  • Server may be overloaded with requests

Now that you understand the issue sits with the server and not the client-side, you can eliminate your device or internet connection when trying to fix the 504 gateway timeout error.

How to Fix the 504 Gateway Timeout Error: 5 Ways

It can be a challenge to figure out what is causing the timeout error. Since this is considered a network error in the server and not with your computer, there are many reasons why the error message popped up, which we’ll talk about later in this article. Here are a few things you can do to try fixing the issue.

1. Reloading Your Website

You can try reloading the website you’re trying to visit. If you’re trying to visit the website on your computer, you can click the refresh button or the F5 key to see if it was just a temporary interruption with the connection. Otherwise, you can also try some of these suggestions.

  • Turn off your VPN, then refreshing the website
  • Try another browser
  • Restart your browser

Some 504 gateway timeout errors happen when the server is temporarily overloaded. By clicking refresh or reload, the website will send out a new request to the server. If it was just a temporary overload or connection issue, the website should load in your browser.

2. Restart All Network Devices

A temporary disruption in your network connection can cause the gateway timeout error. You can try restarting all your network devices, including your modem and router to see if it will fix the issue.

It’s as easy as unplugging both your router and modem, then waiting for 30 seconds before plugging it back in. You’ll have to wait another 60 seconds to start everything up and see if the issue persists.

3. Check The Proxy Server Settings

Check the proxy settings in your browser and application, and make sure they’re correct. Incorrect proxy settings can cause 504 errors. Some computers don’t have proxy settings at all.

If you have Windows 10 or Windows 11, you don’t have to set your proxy settings in each browser. You can check and change the settings directly in Windows 10 or Windows 11, and it’ll apply to Google Chrome, Opera, Microsoft Edge, and Firefox.

Here are the steps:

  1. Open the Start menu and select the gear icon (Settings).
  2. In Settings, select Network and Internet.
  3. In the left-hand pane, click Proxy.
  4. You’ll be able to view all the proxy settings in Windows. Everything should be set to off. If there is something turned on, it means your web traffic is going through a proxy.

The steps are similar if you are using macOS. This will apply to the settings in Safari as well:

  1. Open System Preferences and select Network.
  2. On the left tab, make sure to select the active network connection.
  3. Then click Advanced at the bottom
  4. Select Proxies.
  5. You’ll see a list of proxy servers you’ll be able to configure.

You can follow these steps if you’re using Internet Explorer:

Open Internet Explorer, then click Internet Options.

  1. Click on the Connections tab, then LAN settings to open the LAN settings window.
  2. If you’re using a proxy server with a URL, check the box for “use automatic configuration script”.
  3. Then in the Address field, type the URL.
  4. If you’re using a proxy server with an IP address, check the box for “use a proxy server for your LAN”.
  5. When you’ve made your selections, click OK to save your changes

In most cases, everything in your proxy settings should be set to off, or to “automatically detect settings”. This allows your computer to automatically select the best proxy settings for you.

4. Change DNS Servers

If you’ve tried connecting to the website on other devices but you’re still getting the same error message, you can consider changing your DNS servers. The Google Public DNS server provides a secure DNS connection. You can change your DNS server to some of the free public DNS servers listed below.

  • Google DNS – 8.8.8.8
  • Cloudflare – 1.1.1.1
  • OpenDNS – 208.67.222.222

It’s possible the DNS server you’re using is causing the issue with the 504 gateway timeout error. We’ve listed the steps you can take to change your DNS server.

Changing DNS server on Windows:

  1. Open the Start menu and select the gear icon (Settings).
  2. Once you’re in settings, click Network and Internet.
  3. Select Change adapter options.
  4. Right-click your chosen internet connection and select Properties.
  5. Click Internet Protocol Version 4, then click the Properties button.
  6. Click the item labeled Use the following DNS server addresses.
  7. Enter your two chosen addresses.
  8. Click OK to save your changes.

Changing DNS server on macOS:

  1. Select Preferences from the Apple Menu.
  2. Launch the Network app.
  3. Select your internet connection and click the Advanced button.
  4. In the Advanced window, select the DNS tab.
  5. Use the plus-sign on the right to add your chosen DNS addresses.
  6. Click OK to save your changes.

If you decide to change the DNS server on your router, just remember that this will affect all your connected devices. This also includes smart appliances and home security. Before starting, search “how to change DNS” for the make and model of your router. You’ll need instructions that are specific to your router’s model.

5. Temporarily Disable Your Site’s Content Delivery Network

The content delivery network you’re connecting to can sometimes cause the error message. If the website’s origin server is unreachable, the CDN will try to load the website from its cache. However, some CDNs don’t have this feature enabled as it can be complicated to cache certain assets on websites. An easy way to do this is to temporarily disable your CDN.

The WordPress Popup plugin uses a CDN server to store files like images, and CSS libraries. You can temporarily disable this with the following steps:

  • Head to the WordPress admin area of your website.
  • Under the Settings tab, select the Popup plugin.
  • Activate the “Disable CDN usage” option.
  • Save changes.

If you’re using the Onyx CDN, you can follow these steps:

  • Login to your Onyx dashboard.
  • Select the website you want to disable the CDN for.
  • In the left-hand menu, select CDN.
  • Select the Disable CDN button.

WP Engine utilizes MaxCDN in their CDN offering. It only offloads wp-content directory files including images, CSS and Javascript. If you’re using WP Engine’s CDN, you can use these steps to temporarily disable the CDN:

  1. Log in to the User Portal.
  2. Click Sites.
  3. Select the production environment name.
  4. Select CDN.
  5. Uncheck the box on the right to indicate you’re disabling CDN.
  6. Be sure to save your changes.

Various Examples of 504 Gateway Timeouts (How the Errors Look/What the Differences Are)

There are two main ways the 504 gateway timeout error can show up on your screen. It can be helpful to differentiate between the two to find out where the issue lies.

Certain CDNs, like Cloudflare that provide full proxy services, have additional firewalls between their servers and yours. This may cause you to encounter the error message more frequently.

The error message above usually occurs when the issue is caused by Cloudflare itself. If you see this message, it’s advisable to contact their user support or check their status page.

A custom error message like the one above indicates the issue is with the webserver and not Cloudflare. You can see from the diagram where the issue lies. If you own a website and encounter this message, you can get in touch with your hosting provider for support. 

In Windows-based programs, the 504 gateway timeout error might pop up in a small dialog box with a message saying HTTP_STATUS_GATEWAY_TIMEOUT. A Windows update will generate an error code 0x80244023 or display an error message WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT.

Why Are You Seeing The 504 Gateway Timeout Error Message? 

There are many reasons why you would encounter the 504 bad gateway timeout error message. We’ve listed some of the more common reasons below.

1. Server Issues (Check With Your Host)

One of the reasons why you would encounter the 504 gateway timeout error message is server issues. This is especially common with high-traffic websites like WordPress blogs, e-commerce sites, or online stores. 

There are a few steps you can take to troubleshoot the issue and decide if you should contact your host. 

  1. Try accessing the website from other devices, for example, your mobile phone. If you are able to view the website on your mobile phone, but not your computer, it tells you the problem lies with the settings in your computer and not the server. However, if it does not work on all your devices, you should call your hosting provider for assistance. 
  2. Websites like Downdetector will also be able to tell you if the website is currently experiencing technical issues and if other people are having problems connecting to it. 
  3. You can also do a Google search “is abc.com down” or check Twitter to see if other people are experiencing the same issue. 
  4. It’s recommended for you to check your WordPress host’s status page as well. 

You should check with your host if they have plans or resources to fix this issue if it happens regularly. However, there can be other reasons for the error message. 

2. Firewall Issues 

Improper configuration can cause your server’s firewall to have some errors. It could be that a few of the firewall’s rules are preventing the server from establishing a proper connection. 

You can check your server’s error logs to see if your firewall is the one causing the issues. To view the raw access and WordPress error logs via FTP, you can follow these steps. 

  1. Connect your site via SFTP. 
  2. You’ll see a folder named “logs” in the root folder. 
  3. Your access and error logs will be in that folder. 

3. Slow Server Infrastructure 

The server you’re using to host your website may not have enough resources to handle the traffic. This happens when the server is overloaded, causing it to timeout while trying to load the website. You can fix this by upgrading to a server with better and stronger infrastructure. 

4. Network Connectivity problems 

Issues with the connection between the proxy server and your web server can be the cause of not responding to requests. A load balancer can also cause network connection issues. 

5. HTTP Timeouts

HTTP timeouts happen when the connection between the web server and the client is kept open for too long. If you’re using WordPress websites, this can happen with WordPress imports. One easy way to solve this is to just switch to a better internet connection. 

6. Needs more PHP Workers 

Each website requires different resources. An online business website will require more resources than a blog because it receives more traffic. PHP workers are used to executing your website’s code. If the PHP workers are busy, a queue will build up. If the queue gets too large, the server will forgo old requests for new ones, which causes the 504 gateway timeout error. You can request more PHP workers from your host to avoid this. 

7. Spam, Bots, or DDoS Attacks 

If your website has been attacked by DDoS or spammed by bots, it can overload the server. You can troubleshoot this by requesting a report from your host provider. 

spam, bots and ddos attacks cause 504 error

There are three reports you can look at. The first is the top-end customer’s IP addresses which is useful if you notice your website is suddenly generating a lot of traffic. You can use this to distinguish if the traffic is genuine or if your website has been attacked by bots. 

The second is the requests and bots report. You can compare the number of people visiting your website versus the number of bots. The third report is the cache analysis report. In this report, you can see what requests are missing in the cache. You should try to cache as many requests as possible to provide the best stability for your website. 

8. Corrupted WordPress Database

A corrupted WordPress database or files can cause 504 gateway timeout errors. This can also happen if your website is experiencing security issues or has been hacked. Repairing the database will depend on the problem it’s having. Certain plugins like WP-DBManager can help you diagnose any issues with the database and repair them. 

Troubleshooting (Health Mode)

There are a few ways you can tell if there is a problem with your WordPress database. One of them is the “error establishing a database connection” message. You can troubleshoot the database issues by understanding the common problems we’ve listed for databases. 

  • Connection problems
  • Incorrect credentials 
  • Corrupted database tables or files 
  • Limited or exceeded PHP Memory 
  • Your website has been hacked

Check Your Site’s Plugins, Theme, and Server Error Logs

There is a small chance that third-party plugins can cause server timeouts by queuing up one too many uncached requests. This takes up a lot of PHP workers and can cause the 504 gateway timeout error to occur. 

You can simply troubleshoot this problem by deactivating all your plugins and checking if your site is working properly.

If it does, you’ll then have to enable each plugin and test the site after each plugin has been enabled. You should also ensure your WordPress core, including the plugins and themes, are updated. 

1. Configure Apache or Nginx Settings Properly 

Bugs and faulty plugins in the Apache or Nginx can cause the 504 bad gateway timeout error. You’ll need to analyze the error logs to find out if this is the case. 

2. 504 Gateway Timeout Error on Nginx + FastCGI (PHP-FHM) 

The 504 gateway timeout error is common when using Nginx with PHP-FHM. This usually means the PHP-FHM took a longer time to generate the response. Some of the reasons for this to happen could be: 

  • The web server was overloaded and it took longer than usual to process requests. 
  • The database behind the PHP application was slow 
  • Nginx timeout configuration included small values

A great way to fix this is to increase the PHP maximum_execution_time, and PHP-FHM request termination time. 

3. 504 Gateway Timeout Error on Nginx Proxy 

To fix the 504 gateway timeout error on Nginx proxy, you can try adding these variations to the nginx.conf file: 

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

4. Other HTTP Errors Like 504 Gateway Timeout 

There are other HTTP errors similar to the 504 gateway timeout error. Some of these include: 

  • 500 Internal Server Error
  • 502 Bad Gateway Error 
  • 503 Service Unavailable 

Conclusion

Troubleshooting and fixing a 504 gateway timeout can seem difficult and overwhelming. But there are many ways to fix the error message as long as you know what could be causing it. If you suspect it’s the server causing the issue, you can always contact your host provider to help you. 

Potential topics: 

  • Troubleshooting and repairing WordPress database issues

Categories: Server Management

Please note that this post is over a year old and may contain outdated information.

If you’re experiencing a 504 Gateway Timout on your long PHP scripts, despite having lengthy execution times in php.ini, here are some things you should check.

PHP Config

If you haven’t yet, make sure both max_execution_time and max_input_time in your php.ini file are set to a sufficient number of seconds. For example:

max_execution_time = 600
max_input_time = 600

Apache Config

If you have PHP set correctly, it may be Apache’s config that is timing out. The setting that controls its timeout is not always present in httpd.conf by default, so you may have to add it.

Open up httpd.conf and look for the setting Timeout. If it doesn’t exist, add it on its own line and set it to a sufficient number of seconds. For example:

Timeout 600

PHPMyAdmin

If you’re experiencing the timeout in PHPMyAdmin, keep in mind that it has its own execution time limit ExecTimeLimit. Open up config.inc.php and if it doesn’t exist, add a config option with a sufficient number of seconds like this:

$cfg['ExecTimeLimit'] = 600;
If that config option already exists, edit it to the desired number of seconds.

Comments (11)

Juan Adamuz   Apr 12, 2021
Thanks It worked like a charm!!

Ngalande   Nov 17, 2020
Added Timeout 600 to httpd.conf and it worked like magic! Thanks.

Pyae Sone Phyoe   Nov 03, 2020
Thanks for ur information.

Steve   Oct 16, 2020
Thank you for this… it was definitely this setting that had to be added in, Timeout 600 in /etc/httpd/conf/httpd.conf, to prevent a gateway timeout error with an api server in my app.

Mark   Aug 18, 2020
This post is still useful.
Added Timeout to httpd.conf and it worked.
Thanks

Damilola   Dec 02, 2019
Added Timeout 600 to httpd.conf and it worked!
Thank you.

George   Jul 21, 2018
Thank you, it was very useful!

Sandeep   Jan 31, 2018
Appreciate the post.

Hari   Nov 29, 2017
Thank you for this post.

Nick Vogt   Oct 28, 2015
If you’re on a shared host, you may not have full access to these properties. You can try setting them in your php file or htaccess, but that depends on your server setup. You’ll have to ask them.

Habib Bellia   Oct 27, 2015
and in hosting ?

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

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

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

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

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

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

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

Следует учесть, что не всегда высокая нагрузка обусловлена большим числом посетителей, однако такое встречается не редко. Можете посмотреть статью «Ошибка 502 Bad Gateway — причины возникновения и способы устранения», там подробнее рассмотрены причины возникновения нагрузки.

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

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

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

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

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

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

Схема появления ошибки 504

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

Рассмотрим несколько распространенных случаев и попытаемся понять как исправить 504 -ю ошибку.

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

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

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

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

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

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

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

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

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

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

php_value max_execution_time N

N — в данном случае означает ожидание в секундах.

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

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

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

Рекомендуем ознакомиться:

Подробности

Опубликовано: 28 Сентябрь 2013

Обновлено: 15 Октябрь 2013

Просмотров: 136938

Понравилась статья? Поделить с друзьями:
  • Error 503 роблокс
  • Error 503 unknown method
  • Error 503 site temporarily unavailable modx после переноса
  • Error 503 site temporarily unavailable modx revo
  • Error 503 sans