Ошибка response status code was unacceptable 502

Загружая страницу, браузер отправляет кучу запросов другим серверам. Они обрабатывают все запросы, затем возвращают код ответа HTTP с определенным результатом. Если в процессе этого возникнет какой-то сбой, на экране браузера отобразится ошибка. И одна из таких ошибок – 502 Bad Gateway. Я расскажу, что она означает, по каким причинам выходит, а еще опишу способы ее устранения.

Что означает ошибка 502 Bad Gateway

Ошибки, принадлежащие серии 5xx, означают появление проблем на стороне сервера. Если взять конкретно ошибку 502 Bad Gateway, то ее появление будет означать получение неправильного ответа сервера. «Виновниками» в такой ситуации обычно являются прокси, DNS или хостинг-серверы.

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

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

Подписаться

Что делать, если вы пользователь

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

Перезагрузить страницу

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

Проверить подключение к интернету

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

Очистить кэш и cookies

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

Для любого браузера актуально – зайти в историю просмотров и найти ссылку «Очистить историю». В новом окне отметить пункты с кэшем и cookies, затем подтвердить действие. Как только данные будут удалены, надо вновь попробовать загрузить страницу. Не помогло? Идем дальше!

Очистить кэш DNS

Допустимо, что в кэше установлено неправильное значение IP-адреса. Для таких случаев можно использовать сброс DNS кэша. В ОС Windows необходимо открыть инструмент «Командная строка» (вводим в поисковую строку название программы и выбираем запуск от имени администратора).

Далее следует ввести вот такую команду и активировать ее нажатием на клавишу Enter:

ipconfig /flushdns

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

Как очистить кэш DNS через командную строку Windows

Для Linux действие примерно схоже, но команда выглядит иначе. Открываю утилиту «Терминал» и ввожу в поле вот такой запрос:

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

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

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

Отключить плагины и расширения

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

Зайти на страницу позже

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

Читайте также

Ошибка 400 Bad Request

Что такое ошибка 500 и когда она возникает

Что делать, если вы администратор сайта

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

Проверка журнала ошибок

Актуально в случаях, при которых ошибка 502 Bad Gateway появляется после внесения изменений или обновления. Определить это очень просто, нужно лишь проверить журнал ошибок. В CMS WordPress можно включить запись возникающих ошибок, добавив в файл wp-config.php вот такие строки:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

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

Проверка плагинов

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

Отключение плагина в WordPress путем переименования папки

Проверка сети CDN

Сети CDN и службы предотвращения DoS тоже могут влиять на работу сайта. Обычно виновник проблемы указывается на странице с кодом ошибки. Например, если под кодом 502 Bad Gateway есть строка cloudflare-nginx, значит, для исправления ошибки надо обратиться в службу поддержки CloudFlare. Можно отключить данный сервис, но потом придется долго ждать обновления DNS (это может занять несколько часов).

Один их вариантов отображения ошибки 502 Bad Gateway

Ошибка 502 на виртуальном хостинге VPS/VDS

Ошибка 502 Bad Gateway возникает из-за превышения лимита трафика пользователей, «шалостей» бота, скачивания сайта или даже DoS‑атаки. Решение данной проблемы кроется в ограничениях памяти.

Запустить команду top

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

Посмотреть логи Apache и nginx

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

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

Увеличить объем памяти

Бывает, что с логами все нормально, но памяти на обработку запросов все равно не хватает. Узнать об этом просто – при проверке командой top будет выдана ошибка OOM (out of memory). В таких случаях можно просто увеличить ее объем. Можно просто заказать другой тариф, в котором количество предоставляемой памяти больше. Подробнее об этом.

Проверить лимиты на php-cgi процессы

Если после проверки командой top показано, что свободной памяти еще достаточно, значит, на php-cgi процессы установлены лимиты. Для решения надо открыть конфигурационный файл Apache – httpd.conf, найти секцию модуля FastCGI (mod_fascgi или mod_fastcgid) и увеличить лимит.

Обратиться к службе технической поддержки

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

Загружая страницу, браузер отправляет кучу запросов другим серверам. Они обрабатывают все запросы, затем возвращают код ответа HTTP с определенным результатом. Если в процессе этого возникнет какой-то сбой, на экране браузера отобразится ошибка. И одна из таких ошибок – 502 Bad Gateway. Я расскажу, что она означает, по каким причинам выходит, а еще опишу способы ее устранения.

Что означает ошибка 502 Bad Gateway

Ошибки, принадлежащие серии 5xx, означают появление проблем на стороне сервера. Если взять конкретно ошибку 502 Bad Gateway, то ее появление будет означать получение неправильного ответа сервера. «Виновниками» в такой ситуации обычно являются прокси, DNS или хостинг-серверы.

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

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

Подписаться

Что делать, если вы пользователь

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

Перезагрузить страницу

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

Проверить подключение к интернету

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

Очистить кэш и cookies

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

Для любого браузера актуально – зайти в историю просмотров и найти ссылку «Очистить историю». В новом окне отметить пункты с кэшем и cookies, затем подтвердить действие. Как только данные будут удалены, надо вновь попробовать загрузить страницу. Не помогло? Идем дальше!

Очистить кэш DNS

Допустимо, что в кэше установлено неправильное значение IP-адреса. Для таких случаев можно использовать сброс DNS кэша. В ОС Windows необходимо открыть инструмент «Командная строка» (вводим в поисковую строку название программы и выбираем запуск от имени администратора).

Далее следует ввести вот такую команду и активировать ее нажатием на клавишу Enter:

ipconfig /flushdns

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

Как очистить кэш DNS через командную строку Windows

Для Linux действие примерно схоже, но команда выглядит иначе. Открываю утилиту «Терминал» и ввожу в поле вот такой запрос:

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

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

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

Отключить плагины и расширения

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

Зайти на страницу позже

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

Читайте также

Ошибка 400 Bad Request

Что такое ошибка 500 и когда она возникает

Что делать, если вы администратор сайта

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

Проверка журнала ошибок

Актуально в случаях, при которых ошибка 502 Bad Gateway появляется после внесения изменений или обновления. Определить это очень просто, нужно лишь проверить журнал ошибок. В CMS WordPress можно включить запись возникающих ошибок, добавив в файл wp-config.php вот такие строки:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

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

Проверка плагинов

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

Отключение плагина в WordPress путем переименования папки

Проверка сети CDN

Сети CDN и службы предотвращения DoS тоже могут влиять на работу сайта. Обычно виновник проблемы указывается на странице с кодом ошибки. Например, если под кодом 502 Bad Gateway есть строка cloudflare-nginx, значит, для исправления ошибки надо обратиться в службу поддержки CloudFlare. Можно отключить данный сервис, но потом придется долго ждать обновления DNS (это может занять несколько часов).

Один их вариантов отображения ошибки 502 Bad Gateway

Ошибка 502 на виртуальном хостинге VPS/VDS

Ошибка 502 Bad Gateway возникает из-за превышения лимита трафика пользователей, «шалостей» бота, скачивания сайта или даже DoS‑атаки. Решение данной проблемы кроется в ограничениях памяти.

Запустить команду top

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

Посмотреть логи Apache и nginx

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

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

Увеличить объем памяти

Бывает, что с логами все нормально, но памяти на обработку запросов все равно не хватает. Узнать об этом просто – при проверке командой top будет выдана ошибка OOM (out of memory). В таких случаях можно просто увеличить ее объем. Можно просто заказать другой тариф, в котором количество предоставляемой памяти больше. Подробнее об этом.

Проверить лимиты на php-cgi процессы

Если после проверки командой top показано, что свободной памяти еще достаточно, значит, на php-cgi процессы установлены лимиты. Для решения надо открыть конфигурационный файл Apache – httpd.conf, найти секцию модуля FastCGI (mod_fascgi или mod_fastcgid) и увеличить лимит.

Обратиться к службе технической поддержки

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

Инструкции для пользователей и для администраторов сайтов.

Что такое ошибка 502 и как её исправить

Ошибка 502 Bad Gateway указывает, что сервер, с которым пытался соединиться ваш компьютер или смартфон, получил неверный ответ сервера уровнем выше. Чаще всего это происходит из‑за проблем в работе DNS, прокси или хостинга.

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

Идите от простого к сложному — и в какой‑то момент ошибка, возможно, исчезнет.

Проверьте подключение к интернету

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

Посмотрите, у всех ли отображается ошибка 502

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

Если другого гаджета под рукой нет, можно воспользоваться онлайн‑сервисами. Они покажут, доступен ли сайт у других пользователей:

  • Down for Everyone or Just Me;
  • Is It Down Right Now;
  • Reg.ru;
  • 2IP.

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

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

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

Попробуйте другой браузер

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

Отключите плагины и расширения в браузере

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

Очистите кеш браузера

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

Вот как это сделать в Chrome.

  1. В настройках перейдите к разделу «Конфиденциальность и безопасность» и выберите пункт «Очистить историю».
  2. Поставьте галочки напротив второго и третьего пунктов: «Файлы cookie и другие данные сайтов», «Изображения и другие файлы, сохранённые в кеше».
  3. Затем нажмите «Удалить данные».

Инструкции для остальных браузеров ищите здесь.

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

В Windows 10

  • Чтобы вызвать консоль, напишите cmd в окне поиска меню «Пуск».
  • В открывшемся окне введите команду ipconfig /flushdns и нажмите Enter.

В Windows 7

  • В консоли введите команду ipconfig /flushdns и нажмите Enter.
  • Затем там же выполните команды net stop dnscache и net start dnscache, чтобы перезапустить службу DNS‑клиента.

В macOS

  • Нажмите на иконку поиска в правом верхнем углу и напишите «Терминал».
  • В открывшемся окне терминала введите команду sudo killall -HUP mDNSResponder; sleep 2;.

В Linux

  • Запустите терминал сочетанием клавиш Ctrl + Alt + T или из основного меню.
  • В открывшемся окне введите команду sudo service network‑manager restart и нажмите Enter. Это точно работает на Ubuntu и иногда на других дистрибутивах. Альтернатива — команды sudo systemd‑resolve —flush‑caches или sudo /etc/init.d/nscd restart.

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

Перезагрузите роутер

Зайдите в консоль управления маршрутизатором и найдите соответствующий пункт. Или отключите питание устройства на 10–15 секунд, а затем снова подключите его к электросети.

Измените DNS‑сервер по умолчанию

В настройках роутера укажите адреса публичных DNS‑серверов. Например, можно вписать IPv4 для Google Public DNS: 8.8.8.8 или 8.8.4.4. Или, если ваш сервер поддерживает IPv6, задайте адреса 2001:4860:4860::8888 и/или 2001:4860:4860::8844.

Зайдите позднее

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

Сообщите администратору

Если у вас есть контакты администратора сайта, расскажите ему об ошибке 502. Возможно, он ещё не в курсе проблемы и, соответственно, пока не решает её.

Как администратору исправить ошибку 502

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

Проверьте журнал ошибок

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

Отключите или удалите свежие плагины и компоненты

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

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

Попробуйте отключить анти‑DDoS

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

Но если в этой цепочке что‑то идёт не так, возникает ошибка 502. Попробуйте временно отключить анти‑DDoS — иногда после этого проблема исчезает.

Увеличьте количество ресурсов

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

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

Попросите помощи

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

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

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

Читайте также 💿⚙️💻

  • Что делать, если тормозит браузер
  • Как исправить ошибку CPU Fan Error при загрузке компьютера
  • Что делать, если DNS-сервер не отвечает
  • Что такое ошибка 500 и как её исправить
  • Что означает 404 Not Found и другие ошибки веб-страниц

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

Ошибка 502 Bad Gateway: что значит

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

Ошибка 502 Bad Gateway возникает при неправильной работе прокси-сервера, DNS-сервера и чаще всего сервера, на котором размещён сайт. Проблема может распространяться как на весь ресурс, так и на отдельные страницы. Это зависит от характера проблемы. Существуют разновидности 502 ошибки: Bad Gateway Nginx, Bad Gateway Apache. Об их отличиях мы расскажем ниже. Также эта ошибка может иметь формулировки:

  • Bad Gateway: Registered endpoint failed to handle the request, Temporary Error (502),
  • Error 502,
  • Bad 502 Gateway,
  • 502 Error,
  • 502. That’s an error,
  • 502 Service Temporarily Overloaded,
  • 502 Server Error: The server encountered a temporary error and could not complete your request,
  • 502 – Web server received an invalid response while acting as a gateway or proxy server,
  • 502 Bad Gateway Nginx,
  • 502 Proxy Error,
  • HTTP 502,
  • HTTP Error 502 Bad Gateway.

Что значит плохой шлюз: ошибка 502

Причины возникновения ошибки 502 Bad Gateway

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

  2. Большое количество посетителей одновременно. Веб-ресурс может посещать ограниченное количество посетителей. Сколько человек может посетить сайт зависит от возможностей сервера (размера оперативной памяти) и настроек, которые сделал создатель ресурса. Если по какой-либо причине на сайт зайдёт больше пользователей, чем запланировано, сервис может не справиться и страница выдаст код 502. Такое случается при рекламных акциях и распродажах в интернет-магазинах.
  3. Атака хакеров или DDoS-атака. Эта проблема связана с предыдущей причиной перегрузки. Хакер имитирует большой наплыв пользователей, из-за чего сервер выходит из строя. Такие атаки могут быть использованы для снижения продаж.
  4. Плохая оптимизация сайта. Настройки ресурса сделаны так, что маленькое количество посетителей генерирует много запросов. В этом случае нужно оптимизировать работу сервера с пользовательскими запросами.
  5. Второй причиной возникновения кода 502 могут явиться ошибки РНР. Если для расширения функционала сайта в панель управления были добавлены некорректно настроенные плагины, они могут выдавать проблемы в своей работе. Вместе с ними ошибку покажет и сайт целиком. Также если код сайта написан неправильно, запросы могут давать отрицательный результат.
  6. Ошибка браузера. Проблема может быть на стороне пользователя, если у него установлены расширения, которые нарушают соединение с сервером сайта.

Чем отличается ошибка 502 Bad Gateway Nginx

Между браузером и сервером может стоять веб-сервер. Он используется для снижения нагрузки на сервер, аутентификации пользователей и многого другого. Самые популярные программы для создания веб-сервера ― Nginx и Apache. Так как веб-сервер является посредником между браузером и сервером, то именно он будет оповещать пользователя о проблеме. Поэтому в зависимости от веб-сервера в сообщении вы можете увидеть надпись Bad Gateway Nginx или Bad Gateway Apache. При этом причины возникновения проблемы одинаковы.

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

Что делать, если вы пользователь

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


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

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

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

ipconfig /flushdns

  1. Дождитесь сообщения об очистке кэша:
  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. Попробуйте заново зайти на сайт.

Что делать, если вы владелец сайта

Проверьте количество свободной памяти. Это можно сделать двумя способами.

Способ 1 ― введите команду top в командной строке сервера:

Mem ― вся оперативная память.

Swap ― раздел подкачки.

Посмотрите на строку Memfree. Это количество свободного места на сервере. Если там указано маленькое число, ошибка 502 Bad Gateway появляется из-за нехватки памяти. Увеличьте количество оперативной памяти и проблема пропадёт. Также в результатах можно будет увидеть, какую нагрузку на сервер даёт каждый отдельный процесс.

Способ 2 ― введите команду free -m.

Mem ― вся оперативная память.

Swap ― раздел подкачки.

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

Проверьте логи сервера. Если проблема возникла в момент каких-либо обновлений на сайте, проверьте журнал изменений, чтобы отменить те доработки, которые нарушили функциональность сервера. Также в логах можно увидеть DDos-атаку. Если дело в нехватке памяти, в логах отобразится ошибка OOM (out of memory).

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

  1. 1.

    Войдите в панель управления WordPress. Если вы пользуетесь услугой REG.Site, войти в панель управления CMS можно прямо из Личного кабинета.

  2. 2.

    Перейдите во вкладку «Плагины» ― «Установленные».

  3. 3.

    Нажмите Деактивировать у плагина, который, как вам кажется, повлиял на работу сайта:

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

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

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


Сайт находится на виртуальном хостинге REG.RU

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

  1. Точное московское время наблюдения проблемы.
  2. Название сайта, на котором была замечена проблема.
  3. Если ошибка отображается не сразу, а после определённых действий (добавление изображения, отправка формы с сайта, импорт файлов), подробно опишите порядок действий, по которому мы сможем воспроизвести проблему.
  4. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.


Сайт находится на VPS REG.RU

Чаще всего на VPS используется связка: Nginx + бэкенд-сервер (Apache, PHP-FPM, Gunicorn, NodeJS). Ошибка 502 возникает в случае, если Nginx не может получить ответ от этих сервисов.
Клиенты с VPS сталкиваются с «502 Bad Gateway», когда:

  • какой-то из сервисов выключен. Перезапустите веб-сервер Apache, PHP-FPM либо другой сервис, с которым работает Nginx;
  • между Nginx и бэкенд-сервером некорректно настроена связь. Например, Nginx производит обращение к порту 8080, а веб-сервер Apache «слушает» на 8081. В этом случае необходимо скорректировать настройки веб-сервера.

Если вам не удалось самостоятельно устранить ошибку 502, обратитесь в техподдержку. В заявке укажите:

  1. Точное московское время наблюдения проблемы.
  2. Название сайта, на котором была замечена проблема.
  3. Если ошибка отображается не сразу, а после определённых действий (добавление изображения, отправка формы с сайта, импорт файлов), подробно опишите порядок действий, по которому мы сможем воспроизвести проблему.
  4. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.

When it comes to websites, there are a lot of different errors that can be downright frustrating and confusing. A few that come to mind are the white screen of death or the frightening error establishing a database connection.

But an even more popular one is the 502 bad gateway error. Why? Because this regularly happens around the entire web, not only to WordPress sites, but even popular services such as Gmail, Twitter, and Cloudflare.

Read more below about what causes this error and some solutions on how to quickly resolve it.

  • What Is a 502 Bad Gateway Error?
  • How to Fix the 502 Bad Gateway Error

What is a 502 Bad Gateway Error?

The 502 Bad Gateway error specifically means that the server received an invalid response from an inbound server.

The Internet Engineering Task Force (IETF) defines the 502 Bad Gateway error as:

The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.

Every time you visit a website your browser sends a request to a web server. The web server receives and processes the request, and then sends back the requested resources along with an HTTP header and HTTP status code. Typically an HTTP status code isn’t seen unless something goes wrong. It’s basically the servers way of notifying you that something has gone wrong, along with the code on how to diagnose it.

There are many different types of 500 status error codes (500, 501, 502, 503, 504, 508, 520, etc.) which all have slightly different meanings. These indicate that the request was accepted, but the server prevented the fulfillment of the request.

502 bad gateway error in Chrome

502 bad gateway error in Chrome

Check Out Our Video Guide to The 502 Error

502 Bad Gateway Error Variations

Due to the various browsers, web servers, and operating systems, a 502 bad gateway error can present itself in a number of different ways. But they all have the same meaning. Below are just a couple of the many different variations you might see on the web:

  • “502 Bad Gateway”
  • “Error 502”
  • “HTTP Error 502 – Bad Gateway”
  • “502 Service Temporarily Overloaded”
  • “502 Proxy Error”
  • A blank white screen
  • “502 Server Error: The server encountered a temporary error and could not complete your request”
  • “HTTP 502”
  • Temporary Error (502)
  • 502. That’s an error
  • 502 bad gateway Cloudflare
  • Bad Gateway: The proxy server received an invalid response from an upstream server

Another variation you might see is a “502 server error.”

502 server error in Chrome

502 server error in Chrome

And here is yet another variation. “502 – Web server received an invalid response while acting as a gateway or proxy server. There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.”

502- web server received an invalid response

502- web server received an invalid response

Other services such as Twitter might even show a completely different message for a 502 Bad Gateway error, such as “Twitter is over capacity.” This definitely looks a little more user-friendly.

Twitter is over capacity

Twitter is over capacity (Img src: Softpedia)

And here is a snapshot of how Google displays it. “502. That’s an error. The server encountered a temporary error and could not complete your request. Please try again in 30 seconds. That’s all we know.”

Google 502 error

Google 502 error

502 Errors Impact on SEO

Unlike 503 errors, which are used for WordPress maintenance mode and tell Google to check back at a later time, a 502 error can have a negative impact on SEO if not fixed right away. If your site is only down for say 10 minutes and it’s being crawled consistently a lot of times the crawler will simply get the page delivered from cache. Or Google might not even have a chance to re-crawl it before it’s back up. In this scenario, you’re completely fine.

However, if the site is down for an extended period of time, say 6+ hours, then Google might see the 502 error as a site level issue that needs to be addressed. This could impact your rankings. If you’re worried about repeat 502 errors you should figure out why they are happening to begin with. Some of the solutions below can help.

How to Fix the 502 Bad Gateway Error

A 502 bad gateway error is typically a problem with the network/server, however, it can also be a client-side issue. So we’ll dive into a little of both. Check out these common causes and ways to fix the 502 bad gateway error to and get back up and running.

1. Try Reloading the Page

One of the easiest and first things you should try when encountering a 502 bad gateway error is to simply wait a minute or so and reload the page (F5 or Ctrl + F5). It could be that the host or server is simply overloaded and the site will come right back. While you’re waiting, you could also quickly try a different browser to rule that out as an issue.

Another thing you can do is to paste the website into downforeveryoneorjustme.com. This website will tell you if the site is down or if it’s a problem on your side.

downforeveryoneorjustme

downforeveryoneorjustme

2. Clear Your Browser Cache

Whenever you encounter issues like these it can be good to clear your browser cache. Below are instructions on how to do it in the various browsers:

  • How to Force Refresh a Single Page for All Browsers
  • How to Clear Browser Cache for Google Chrome
  • How to Clear Browser Cache for Mozilla Firefox
  • How to Clear Browser Cache for Safari
  • How to Clear Browser Cache for Internet Explorer
  • How to Clear Browser Cache for Microsoft Edge
  • How to Clear Browser Cache for Opera

3. DNS Issue

A 502 gateway error could also be because of a DNS issue, such as the domain is not resolving to the correct IP, or the DNS server is not responding. If you have just migrated your site to a new host, is it important to wait for things to fully propagate, which can take up to 24 hours in some cases. This depends upon the TTL value of your DNS records.

You can also try flushing your local DNS cache. This is similar to clearing your browser cache.

In Windows simply open up Command Prompt and enter the following:

ipconfig /flushdns

Command prompt - flush DNS

Command prompt – flush DNS

You should see a “Successfully flushed the DNS resolver Cache” if it worked.

For macOS users, you can enter the following in the terminal:

dscacheutil -flushcache

Note: There is no success message on Macs.

And lastly, you could temporarily change your DNS servers. By default, DNS servers are automatically assigned by your ISP. But you could try temporarily changing these to a public DNS server, such as Googles. In fact, some prefer to use Google’s public DNS long-term. If you have a premium DNS propagation usually is a lot faster.

4. Check With Your Host

The primary reason we typically see a 502 bad gateway error is due to an issue with the web host. Sometimes a query, script, or request will take too long and so it is canceled or killed by the server. A lot of hosts, especially shared hosts implement what they call a “kill script.” Basically what this does is it will terminate a request after a certain period of time so that it doesn’t take a site down or impact other users. If you do a Twitter search for “bad gateway” you can see thousands of tweets happening every day alerting their hosting company of the problem.

502 bad gateway tweets

502 bad gateway tweets

One reason you might want to consider moving to a host like Kinsta is that our platform runs in an isolated software container that contains all of the software resources required to run the site (Linux, NGINX, PHP, MySQL). This means that the software that runs each site is 100% private and is not shared, even between your own sites. This greatly reduces the chance of seeing a 502 bad gateway error. We aren’t running aggressive kill scripts like some shared hosts are. And even if one of your sites does happen to go down, it won’t impact your other sites.

Another reason you could see a 502 gateway error with your host is also due to the fact that the server is simply not reachable, either because it is down or there is no connectivity. In this case, it is recommended to check your host’s status page or open a support ticket.

5. Temporarily Disable CDN or Firewall

It could also be an issue with your content delivery network (CDN) or firewall. If you are using a 3rd-party CDN provider an easy way to troubleshoot this is to simply disable your CDN temporarily. For example, we are big fans of the free CDN enabler plugin. If you are using that, you can simply deactivate the plugin and then test your site. Wp-admin not working? Simply log in to your site via SFTP and rename the plugin’s folder to cdn-enabler_old. This will temporarily disable the CDN connection. The same goes for WP Rocket or any other plugin you might have hooked up to your CDN.

Rename plugin folder temporarily

Rename plugin folder temporarily

This can also occur sometimes with providers that provide DDoS protection and mitigation or fully proxy services like Cloudflare, as they have extra firewalls in-between. We have noticed that this happens once in a while on the Cloudflare free plan. Unfortunately, since Cloudflare is a fully proxy service, there is no quick way to simply disable it.

However, before you go blaming Cloudflare, it is important to know that there are two different types of 502 bad gateway errors variations with Cloudflare as seen below:

502 Bad Gateway at Cloudflare (Variation 1)

If you see the following screen, this is actually a problem on Cloudflare’s end, in which case you should reach out to them for support. You can also check Cloudflare’s status page to see if they’re currently experiencing an outage.

502 bad gateway error

502 bad gateway error

502 Bad Gateway at Cloudflare (Variation 2)

If you see the following screen, this is a problem with your host.

Cloudflare 502 bad gateway at host

Cloudflare 502 bad gateway at host

GoDaddy Firewall

Here is another example with of an HTTP 502 error and GoDaddy’s firewall. The issue is actually with the origin server (the hosting provider) due to a timeout, not the firewall itself.

HTTP 502 - GoDaddy Firewall

HTTP 502 – GoDaddy Firewall

6. Check Your Plugins and Themes

A lot of times the reason for scripts and queries being canceled by the server is due to bad code on your WordPress site, possibly from a 3rd party plugin or theme. We have also seen a lot of misconfigured caching plugins generate 502 errors. A few ways you can troubleshoot this is by deactivating all your plugins. Remember, you won’t lose any data if you simply deactivate a plugin.

If you can still access your admin, a quick way to do this is to browse to “Plugins” and select “Deactivate” from the bulk actions menu. This will disable all of your plugins. If this fixes the issue you’ll need to find the culprit. Start activating them one by one, reloading the site after each activation. When you see the 502 gateway error return, you’ve found the misbehaving plugin. You can then reach out to the plugin developer for help or post a support ticket in the WordPress repository.

Deactivate all plugins

Deactivate all plugins

If you can’t access your admin you can FTP into your server and rename your plugins folder to something like plugins_old. Then check your site again. If it works, then you will need to test each plugin one by one. Rename your plugin folder back to “plugins” and then rename each plugin folder inside of if it, one by one, until you find it.

Rename plugin folder

Rename plugin folder

Always makes sure your plugins, themes, and WordPress core are up to date. And check to ensure you are running a supported version of PHP. You can always reach out to your host for assistance. We use Kinsta APM and other troubleshooting methods here at Kinsta to help clients narrow down what plugin, query, or script might be causing the error. You can also use your own custom New Relic key if you have your own license.

Time consuming queries to database

Time-consuming queries to the database

If it turns out to be an efficient query or bad code in a plugin, you might need to bring in a WordPress developer to fix the issue.

7. Check Logs

You should also take advantage of your error logs. If you are a Kinsta client, you can easily see errors in the log viewer in the MyKinsta dashboard. This can help you quickly narrow down the issue, especially if it’s resulting from a plugin on your site.

Check error logs for 502 bad gateway errors

Check error logs for 502 bad gateway errors

If your host doesn’t have a logging tool, you can also add the following code to your wp-config.php file to enable logging:

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

If you need more help on how to enable WordPress debugging mode here is a full step by step tutorial.

The logs are typically located in the /wp-content directory. Others, like here at Kinsta might have a dedicated folder called “logs”.

wordpress error logs folder sftp

You can also check the log files in Apache and NGINX, which are commonly located here:

  • Apache: /var/log/apache2/error.log
  • NGINX: /var/log/nginx/error.log

If you are a Kinsta client you can also take advantage of our analytics tool to get a breakdown of the total number of 502 errors and see how often and when they are occurring. This can help you troubleshoot if this is an ongoing issue, or perhaps something that has resolved itself.

Response analysis 500 error breakdown

Response analysis 500 error breakdown

8. Restart PHP

Finally, you can also try restarting PHP. If you’re a Kinsta client, you can easily restart PHP from the tools menu within the MyKinsta dashboard. If your host doesn’t provide this, you can always open up a support ticket and ask them restart PHP.

Restart PHP

Restart PHP

9. PHP Timeout Issue

PHP timeouts occur if a single PHP process runs for longer than the max_execution_time or max_input_time set in the PHP configuration on your server.  This is a common occurrence if you’re doing big WordPress imports. When this happens a 502 server error is usually displayed. If you run into a PHP timeout these values may need to be elevated.

You can check with your current host about what values are set on your server and if they can be increased. On the Kinsta platform, these values are set to 300 seconds (5 minutes) by default. The maximum PHP timeout values available on our platform are based on your current hosting plan.

Summary

As you can see there are quite a few things you can do to troubleshoot and fix a 502 gateway error on your site. Typically this is not on the client-side, but rather an issue with your host. Third-party plugins and themes with bad code or unoptimized queries are also things to watch out for. Was there anything we missed? Perhaps you have another tip on troubleshooting 502 gateway errors. If so, let us know below in the comments.


FAQ

What Is a 502 Bad Gateway Error?

The 502 Bad Gateway error indicates that the server received an invalid response from an inbound server.

What Causes the 502 Error?

The 502 bad gateway error is typically caused by issues related to the network/server, however, it can also be caused by client-side issues.

How Do You Fix the 502 Bad Gateway Error?

There are a number of things you can try when attempting to fix the 502 Bad Gateway Error:

1. Try Reloading the Page
2. Clear Your Browser Cache
3. flush your local DNS cache
4. Check With Your Host
5. Temporarily Disable CDN or Firewall
6. Check Your Plugins and Themes
7. Check Your Logs
8. Restart PHP
9. PHP Timeout Issue


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

HTTP 504 Gateway Timeout and HTTP 502 Bad Gateway errors are the most common server errors for WordPress website visitors and owners. In my previous article, we’ve already discussed the causes of a 504 Gateway Timeout error and possible solutions for it. In this article, we’ll come to understand what a 502 Bad Gateway error is, talk about the reasons for a 502 Bad Gateway error, and explore some tips for troubleshooting this type of errors.

What does 502 Bad Gateway mean?

Before we define what a 502 Bad Gateway error is, let’s deep-dive into server infrastructure and find out the meaning of some terms, like web server, proxy server or gateway, and upstream server.

Let’s first discuss how hosting a modern web application works. For this we need three actors:

  1. The web application
  2. The gateway
  3. The web server

In the picture below you can see the PHP modern web application workflow.
web application workflow
A web application is application software that can be coded in different programming languages and can use specific frameworks or libraries. It typically has tools to handle HTTP requests. For your WordPress website, the web application is your WordPress installation which is coded in PHP.

The gateway sits between a web server (Nginx, Apache) and a web application. It accepts requests from a web server and translates them for a web application. The exact definition of a gateway is somewhat fluid. Some call themselves process managers, some call themselves HTTP servers.

Here’s what the common functionality of a gateway entails:

  • Listening for requests (HTTP, FastCGI, uWSGI, and more)
  • Translating requests to application code
  • Spawning multiple processes and/or threads of applications
  • Monitoring spawned processes
  • Loading balance requests between processes
  • Reporting/logging

PHP-FPM (PHP-FastCGI Process Manager) is the gateway for PHP. It is an implementation of FastCGI and will listen for FastCGI requests from a web server.

FastCGI is a binary protocol for interfacing interactive programs with a web server. CGI (Common Gateway Interface) is a web technology and protocol which describes a way for a web server to communicate with external applications, e.g. PHP. CGI is an interface between the web server and the dynamic web content that is generated by web applications that are written in different programming languages, such as PHP, Python, etc. FastCGI is an improved version of CGI.

A modern way to run PHP applications is to use PHP-FPM. Before PHP-FPM, PHP was commonly run directly in Apache, there was no need for a gateway. Apache’s PHP module loaded PHP directly, allowing PHP to be run in line with any processed files.

The web server generally hosts multiple sites, serves static files, proxies requests to other processes, performs load balancing and HTTP caching. The most popular web servers are Apache and Nginx. Apache used to be the most widespread web server until Nginx became more popular.

At 10Web we support LEMP stack, which is similar to LAMP (Linux, Apache, MySQL, and PHP), except Apache is replaced with Nginx. What happens when you open your WordPress website hosted by 10Web in your browser? The web server, in this case, Nginx, accepts a request and relays it to PHP-FPM, which in turn interprets the PHP code. The response is relayed back, finally reaching the client. In this case, Ngnix acts like a proxy server which in most cases is called an edge server. The server behind the proxy server is called upstream or origin server. In this case, PHP-FPM acts as an upstream server.

Now that we fully understood the above-mentioned terms, let’s finally understand what the 502 Bad Gateway error is.

What is a 502 Bad Gateway error?

We face a 502 Bad Gateway error when the web server acts as a proxy server and receives an invalid response from the upstream server. A 502 Bad Gateway error indicates that the proxy server, which is the edge server, was not able to get a valid response from the upstream server, which is the origin server. When you see a 502 Bad Gateway error it means that something is wrong with the upstream server. This can happen because of various reasons which we’ll cover in this article.

The different forms of 502 errors

A 502 Bad Gateway error can appear in different ways depending on the operating system, web browser, and device. Here’s how it looks most of the time:
502 bad gateway error
Some websites customize 502 Bad Gateway pages. Here’s Google’s:
Google 502 Bad Gateway error
Platforms can also change the message of the error. So you can encounter different messages for the same error but they all have the same meaning:

  • 502 Bad Gateway
  • HTTP Error 502 Bad Gateway
  • Error 502
  • HTTP 502
  • HTTP Error 502 – Bad Gateway
  • 502 Proxy Error
  • 502 Server Error: The server encountered a temporary error and could not complete your request.
  • 502 Bad Gateway NGINX
  • 502. That’s an error. The server encountered a temporary error and could not complete your request. Please try again in 30 seconds. That’s all we know.

What are the reasons behind the 502 Bad Gateway error?

The 5xx status codes indicate that there are problems with the server, and 502 is not an exception. For some reason, the proxy server can’t get a response or a valid response from the upstream server. In your WordPress website with Nginx/PHP-FPM stack, a 502 error can happen when PHP-FPM is not running or Nginx can’t communicate with PHP-FPM for some reason. This case should be checked by your hosting provider. Another reason could be PHP-FPM timeout issues, which we’ll discuss down the line.

Any misunderstanding between Nginx and PHP-FPM can lead to a 502 Bad Gateway error. Though these errors are connected to server-side issues, there are some tips for troubleshooting on the client side.

Let’s go over both client- and server-side troubleshooting.

How to Troubleshoot a 502 error message

Here are some very simple ways of fixing 502 Bad Gateway errors from the client side.

Reload the page

The first thing you should do is reload the page and wait for a minute. If the 502 Bad Gateway error disappears, it means there was a temporary problem with the upstream server or the networking between servers. If the error remains, check if the site is down for everyone. You can use Is it down right now? for this. If the site is up for everyone except you, open the site on another browser or in private mode.

Clear browser cache

Another easy tip is to clear the browser cache. If the error disappears after cleaning cache, it means that there was a temporary problem that has been resolved, but because of cache, you kept seeing the 502 Bad Gateway error template, instead of your website. If the error remains, try the next tip.

Flush DNS cache

The 502 Bad Gateway error can occur because of DNS issues. Operating systems, such as Linux, Windows, and macOS save name resolution information in the form of a DNS cache. In many cases clearing the DNS cache can solve a 502 Bad Gateway error. Here are the commands which you can use for flushing DNS cache on Windows, MacOs, and Linux.
Use this command to flush cache on Windows:

ipconfig /flushdns

On macOS, you should open the terminal and type:

sudo killall -HUP mDNSResponder

There’s no message after processing this command, but you can add your own by running the command like this:

sudo killall -HUP mDNSResponder; dns cleared successfully

Things are different in Linux, as different Linux distributions use different DNS services. Some of them are NSCD (Name Service Caching Daemon), dnsmasq, and BIND (Berkeley Internet Name Domain). 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 for your password, just enter it.

Change DNS servers

You can also try to temporarily change your DNS servers. More information about changing DNS servers can be found in this article: Change your DNS servers settings.

If you’re using Cloudflare

Cloudflare returns a Cloudflare-branded HTTP 502 error when your origin web server responds with a standard HTTP 502 bad gateway:
502 bad gateway appearance
This means that something is wrong with your origin server and you can try to use the above-described tips to fix the issue.

If the 502 error is from Cloudflare, the page looks like this:
bad gateway error cloudfare
If the error contains the word “Cloudflare,” the problem comes from Cloudflare, otherwise, it is from the origin server. In the first case, you can contact Cloudflare support, and in the second case, you can follow the described tips. If nothing helps, contact your hosting provider. You can read more about Cloudflare 5xx errors in the article Troubleshooting Cloudflare 5XX errors.

We’ve discussed some client-side tips which can help you troubleshoot a 502 Bad Gateway error. Now let’s see what you can do on the server-side.

Restart PHP

The very first step is to restart your PHP. With 10Web, you can do this by going to Hosting Services > Tools and clicking the blue “Restart PHP” button.
10Web restarting php bad gateway error
If your hosting doesn’t provide an interface for restarting PHP, ask them to do it for you.

Check logs

Checking your server error logs can give you very useful information about 502 Bad Gateway errors. With 10Web, you can easily check server logs by going to Hosting Services > Logs.
10Web logs hosting services
If you have access to your file system, you can check server logs. In the case of the Nginx web server, you can find logs here:

/var/log/nginx

In the case of Apache web server, the logs are in this repository:

/var/log/apache2

Improper firewall configuration

Improper firewall configuration can lead to 502 Bad Gateway errors. A firewall is a network security system that monitors and controls the incoming and outgoing network traffic based on predetermined security rules. It typically establishes a barrier between a trusted network and an untrusted network.

There can be cases that some awkward firewall settings can consider safe and valid content malicious and, consequently, cut off traffic which in turn cause 502 Bad Gateway errors. Check your firewall configuration to reveal any improper configs.

Third-party plugins & themes

Non-optimal codes in WordPress plugins and themes can also cause 502 errors. So, check your plugins and theme. If you have access to your WordPress admin, deactivate all your plugins, and if the error disappears it means that there is at least one guilty plugin. Then activate them one by one to find the guilty ones. If your WordPress admin area can’t be reached because of the error but you have access to your WordPress files, just rename the plugins directory in wp-content. It will deactivate all plugins. And again start activating them one by one.

If the problem isn’t the plugins, that is deactivating all plugins or renaming plugins directory doesn’t change anything, try to temporarily change your theme to WordPress’s default theme. Once you find the bad plugins or theme, connect to the respective support team and describe the issue.

And don’t forget to keep your plugins, theme, and WordPress core up-to-date. This will help you avoid many problems, including 502 errors.

Restart PHP-FPM service

You will get a 502 error if the PHP-FPM service is inactive or not running on your server. If you have access to your hosting, you can check this by running one of the following commands. For SysVinit:

sudo service php7.4-fpm status

For SystemD:

sudo systemctl status php7.4-fpm

If the service is active and running, the output of the command should be like this:
fixing 502 bad gateway error server-side
If the status is not Active: active(running), try restarting PHP-FPM service to resolve the error using one of the following commands. For SysVinit:

sudo service php7.4-fpm restart

For SystemD:

sudo systemctl restart php7.4-fpm

Timeout issues

The 502 error can be caused by a PHP-FPM timeout. If your application is taking too long to respond, your users will experience a timeout error. If the PHP-FPM timeout is less than Nginx timeout, Nginx will return a 502 Bad Gateway error. To avoid this, you can increase PHP-FPM timeout if you have access to your server.

PHP-FPM timeout is set in pool configuration which is

request_terminate_timeout

The default value for this directive is 20 seconds. If you don’t have access to your server, ask your hosting provider to check it. To avoid getting 504 errors after increasing PHP-FPM timeout which can be because of Nginx timeout, the default is 60 seconds, you can increase fastcgi_read_timeout directive in /etc/nginx/nginx.conf file. Don’t forget to reload the Nginx server after changing the directive:

nginx -s reload

PHP execution time errors can also lead to 502 Bad Gateway errors. To avoid this, you can increase the PHP configs, such as max_exexution_time and max_input_time.

If you have your server access, just change these directives in your php.ini file. If not, ask your hosting provider to do it for you.

FAQs

What is the difference between a 404 error and a 502?

A 404 Not Found error occurs when content can’t be found by the web server. A 502 Bad Gateway error happens when the proxy server can’t get any response or gets an invalid response from the upstream server. You come across 404 when requested content was removed or doesn’t exist. You see 502 errors when there is an issue with the upstream or origin server or a communication issue between proxy and upstream servers.

What is the difference between 502, 503, and 504 error messages on websites?

You got a 502 Bad Gateway error when the proxy server doesn’t get a valid response from the upstream or origin server. 504 Gateway Timeout error happens when the server which is acting as a proxy server can’t receive a timely response from the upstream server. 503 Service Unavailable error indicates that the server is not ready to handle the request, this happens when the server is down for maintenance or is overloaded.

Do 502 errors have any impact on website rankings?

The 502 Bad gateway error can have a major impact on website rankings. You don’t have to worry about a negative impact on SEO if the error lasts a few minutes. If the page is being crawled during this time, the crawler can load it from the cache. But you do need to worry if this error lasts for a few hours. In that case, Google will see the 502 error which can negatively impact your rankings.

What can I do when PHP is working in the command line but returns a 502 error in the browser?

502 error happens because of bad communication between proxy and upstream servers. When you’re running PHP in the command line you don’t need a web server, PHP works for you directly. To find out the reasons for 502 errors, read the above-described tips.

Conclusion

Now you have a complete understanding of what 502 errors are and why they appear on your website. We’ve discussed the various possible reasons for these errors and described many troubleshooting approaches that’ll help you find a solution.

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

The 502 bad gateway error is a type of HTTP error that notifies the user that there is some kind of problem in reaching the requested web page.

The causes of this error are varied, and it is one of several problems that fall under the category of server-side errors. In this article,  we are going to see the reasons for this kind of error, how to detect it and what solutions we have at hand to solve it.

We’ll see what we can do in order to solve or avoid the problem both in case we are surfing on someone else’s website and in case the error is found by a user surfing on our website.

In addition, we will see what specific strategies we can implement when we encounter the 502 bad gateway error in WordPress.

502 bad gateway: the meaning of the error

While browsing, your browser sends requests to a server, which in turn manages incoming requests and provides the response with codes indicating the status of the request.

When the request is successful, the server responds with code 200, but it does not appear to the user. For this reason, when the procedure is completed correctly, the only thing you’ll see is the content of the site or page you intended to visit.

If, however, there is an error, you will be shown a notification warning you about the type of error encountered. In some cases, you will be shown a generic error, for example when browsing with Chrome you may encounter the classic Chrome Aww Snap error. In other situations, you may have to use the Windows network diagnostics to identify the cause of the error, for example, if the DNS server is not responding.

In other situations, however, the error message will also contain a number corresponding to a type of problem: for example, codes with error 400 are client-side errors. One of the most classic examples is when a page is not found and error 404 is shown or error 403 when you are denied access to the server.

Conversely, those ranging from error 500 to 511 are server-side errors. Among them, there is also the 504 gateway time-out that always involves the server. But what does it mean?

Let’s first make a premise by briefly explaining how the network works. As we said when you try to open a site your browser sends a request to a server, this works as a proxy and connects to the server on which the site is hosted.

When the process of handling the request encounters some kind of error, you will be shown a corresponding error code, warning you that something has gone wrong.

502 bad gateway: variants of the same error

This type of error is called error 502 bad gateway because 502 is the HTTP status code that is used to identify the problem in question.

Error 502 can be accompanied by other captions that help denote it better, for example, “bad gateway” or “502 bad gateway nginx” or “502 bad gateway apache“.

In other cases, however, this type of error might appear simply as “Error 502” or “502 Proxy Error”. In almost all cases, however, the error code is specified and this helps us to understand what kind of problem we are experiencing and especially to distinguish it from other types of errors.

Error 502 can have different wording, the most common ones are:

  • Error 502
  • 502 Error
  • 502 server error
  • 502 Bad Gateway
  • 502 Bad Gateway Nginx
  • 502 Bad Gateway Apache
  • 502 bad gateway Cloudflare
  • HTTP 502
  • HTTP Error 502 – Bad Gateway
  • 502. That’s an error
  • 502 Proxy Error
  • 502 Service Temporarily Overloaded
  • 502 Server Error: The server encountered a temporary error and could not complete your request
  • Temporary Error (502)
  • 502 – Web server received an invalid response while acting as a gateway or proxy server
  • Bad Gateway: The proxy server received an invalid response from an upstream server
  • A blank white screen.

Error 502 bad gateway is one of the most frequent problems that can be encountered while browsing and it indicates that the server fails to forward the request to the main server.

However, it is not clear at what point in the process exactly the error occurs. The causes of this error message, in fact, are varied, let’s see what they are.

What causes the 502 bad gateway error

Error 502 bad gateway belongs to the category of generic errors that fall under the 500 codes, but it is a communication error between servers, so these errors are to be attributed to the server and not to the client.

In many cases, therefore, as users, we will have little to do to solve this type of problem. However, as we will see, there are several causes that lead to this kind of errors, some of which can be solved.

In particular, in the case of the 502 bad gateway error, the problem is due to the fact that the server acting as a proxy or gateway has received an invalid response from the server hosting the site. But what is this incorrect response due to?

A system crash of the server

The non-response or invalid response received by the gateway from the server may be due to the fact that the server has suffered a system crash.

More rarely, there may be cases where the server has been taken off the web. In this case, therefore, the error depends on the destination server, i.e. the one hosting the site.

Server overload

One of the most frequent reasons that can lead to the 502 bad gateway error is a server overload that cannot handle the numerous requests received.

This can be due to either a true overload of users or a DDoS attack, by hackers trying to “DDoSing”  the server.

Programming errors

Even an error present in the PHP programming of the target site can go on to generate a failure to resolve requests received from the server and thus cause a 502 error.

A firewall problem

Even firewalls can generate errors, and besides being in some cases responsible for client-side errors such as the dns_probe_finished_nxdomain, can also be the cause of server-side errors.

For example, this error may be due to an incorrectly configured firewall, which therefore prevents proper communication between the gateway and the server.

A browser error

The real culprit of the 502 bad gateway error, at least in some cases, could be the browser itself that you are using. On certain occasions,  the browser or the extensions used in it can generate errors, including the error code in question.

502 bad gateway: fixing the error

Now that we have analyzed what 502 bad gateway means and what are its main causes, let’s see what operations you can do to solve the problem.

502 Bad Gateway Server Error

As it is easy to see, addressing this problem can be useful both to those who take care of their website and to the user who comes across the error. So let’s see what solutions you have available in the two cases.

502 bad gateway error: how to solve by user

The first solutions that I propose in this part of our article can be applied in case you want to try to solve, or avoid, the error 502 bad gateway. First of all, it must be pointed out that, in most cases, this is a temporary error, so it is likely that within a short time the error will disappear on its own.

However, there are several strategies you can use to get around this problem if you need to or if the error lasts longer. Let’s see how.

Reloading the page

The first, and simplest, thing to do when faced with a 502 bad gateway error is definitely to try reloading the web page. So, wait at least a minute and then reload the page in your browser through the appropriate button, or by pressing F5, the shortcut key that works in most browsers such as Google Chrome, Mozilla Firefox, etc. for computers with Windows and Linux operating systems.

If you are using MacOS, you can use the Command + R key combination to refresh pages in most browsers (Safari, Chrome, Firefox, etc.).

In the event of a server overload, it will not be enough to reload the page after a few minutes, but you will have to wait about fifteen minutes for the server to be “available” again.

Emptying the browser cache

Just as I explained to you about the causes that can generate this problem, in some cases, the browser can be responsible for this error. For this reason, another possible solution to solve the 502 bad gateway error is to try clearing your browser’s cache.

The operation varies from one browser to another, but in most programs, you can also clear the cache of even a single page. To do this just use the key combination CTRL + F5, this way only the cache of the page you are visiting is emptied, while the rest remains unchanged.

This key combination works on Windows and Linux, on Mac instead to “bypass” the cache you need to hold down the Command and Shift key and press R at the same time.

In a dedicated article, I explain, instead, how to clear the cache of the main browsers with the procedure step by step.

Use another browser or reinstall the one you are using

Sometimes changing browsers may be required to rule out the possibility that the cause of the problem is the very browser you are using. In this case, if the site is reached without errors using a browser other than the one you usually use, it may be necessary to reinstall it to restore the basic settings.

Before reinstalling the browser, however, you can check that there are no plugins or extensions that interfere with its proper functioning.

Start the browser without extensions

To verify that the cause of the 502 bad gateway error is not due to interference from extensions you will have to disable them, at least momentarily, and see if the problem occurs again.

This is also one of the ways you can use to solve other types of errors like err_connection_refused.

When using Chrome, for example, you can use incognito browsing or private browsing which will automatically disable the various extensions and thus see if the error recurs.

In Firefox, on the other hand, you can start the troubleshot mode (also called safe-mode) that will let you start the browser without the additional themes and extensions. To start this mode you can go to the “Help” options from the menu with the three dashes and select the item “Troubleshoot Mode…”.

502 Bad Gateway Firefox Troubleshoots Mode

After that you’ll just have to confirm by clicking on “Restart”.

502 Bad Gateway Restart Firefox Without Addons

Alternatively, you can also start Safe Mode from the Command Prompt on Windows or from the terminal on Linux or Mac. For Windows computers there are several ways to start the Command Prompt: on Windows 10 you just have to search for it in the search bar and press enter, or, in general, from “Run” you just have to type “cmd”.

502 Bad Gateway Prompt

Once the Command Prompt is open you can start both Firefox and other browsers in safe mode directly with the specific commands.

In the case of Firefox you will have to enter the path of the executable file (firefox.exe) of the browser (C:Program FilesMozilla Firefoxfirefox.exe) followed by the topic – safe-mode. And then you’ll have to click on “Open” as shown in the example below.

502 Bad Gateway Firefox Troubleshoot Mode

After starting the browser in safe mode, if you can access the site without running into the 502 bad gateway error again, then most likely the problem was caused by some extension. If, on the other hand, the problem recurs, then it does not depend on the extensions or themes you have installed on your browser.

In the first case, in order to find the extension that is responsible for the error, you have to disable them one by one until you find the one that causes the problem. In order to do that you will have to access the Extensions panel by clicking on the menu (corresponding to the symbol with three dashes), then on Add-ons and from there select Extensions from the menu on the left.

502 Bad Gateway Firefox Extensions

Then you can click on the button next to each extension to disable/reactivate it.

502 Bad Gateway Deactivate Firefox Extensions

NOTE:  When the extensions are active the icon is blue and it appears in the list of active extensions.For the deactivated ones the icon is grey.

Remember that most of the errors generated by plugins (but also by themes and extensions in general) can be due to their obsolescence, for this reason always remember to keep them updated.

Restarting your router and/or pc

In case the site is online and your computer can’t access it, even though you have tried using different browsers, it may be helpful to try restarting your router and computer. In this case, if it is a temporary problem, it may resolve on its own.

However, the question is, how can you tell if the site you are trying to visit is really online or if the problem is upstream? Well, let’s see in the next paragraph.

Check if the site is working for others and not for us

When you are faced with a 502 bad gateway error, it can be useful to know if the site you are trying to reach is online.

To know if the site you’re trying to visit is active or not you can use one of the services provided by the network such as the one offered by Down for Everyone or Just Me. Just copy and paste or type the address of the site in the search bar to see if it is online or not. In this way you’ll understand if the problems you’re experiencing are actually due to the server that hosts the site or to other causes.

Error 502 Bad Gateway Down For Every One Or Just Me

Another service that you can use to check if a website is active is Is It Down Right Now, also in this case using it is very simple. All you have to do is enter the domain of the website you’re interested in and you’ll get information about the current status, the response time and the last time the website was offline.

Error 502 Bad Gateway Status Check

Change DNS server

Another possible cause of the 502 bad gateway error is a DNS server problem, in this case, manually change the DNS to get around the problem. Changing DNS servers from those offered by your provider to public ones, such as Google or Cloudflare ones can solve your problem. To change DNS servers on Windows and Android I refer you to the detailed procedure described in my article on how to fix DNS_PROBE_FINISHED_NXDOMAIN error.

Access to the cache copy of the site

If you are unable to access the website you are looking for, and the error 502 bad gateway remains even if you have tried the various solutions proposed so far, know that you have the possibility to access the last version of the site saved in the cache of search engines.

In some cases you can also exploit the cache of search engines, such as Google and Bing, to find pages or entire sites no longer online. To do this, after searching for the site that interests you on Google, for example, you just click on the down arrow next to the address of the site and then click on “Copy Cache”.

502 Bad Gateway Google Cache

Similarly, if you use Bing as your search engine, just click on the arrow next to the address and then on “Cached”.

502 Bad Gateway Bing Cache

Error 502 bad gateway how to solve by webmaster

If you are not experiencing the 502 bad gateway error yourself, but a user is unable to access your website, you should try to identify the cause of the error.

After verifying that your server is up, the first thing you can do if your site is down is to contact your hosting service.

Check that there are no problems with the host

In most cases, the 502 error may be due to the hosting service on which your website is based on. There are cases where scripts have to be loaded in order to reach a page, but they take too long.

Some hosting services use a system, called kill script to stop these requests that take longer than necessary.

This type of script, used in some cases by shared hosting, can generate errors and prevent access to shared sites or resources.

Check error logs

The 502 bad gateway error can also be due to internal errors present on your site. The first thing you can do to make sure there are no such issues is to go check the error log. If you’re using WordPress, you can enable the error log and keep track of what’s happening on your site. To do this you’ll need to edit the wp-config.php configuration file by going to add the following code:

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

Check PHP programming

Another thing to do is to check the PHP programming of your site for errors.

For example, you can check that there are no timeout issues that go to terminate some processes, in a scheduled manner, after a certain period. To do this you will need to check your PHP configuration and determine if you should set a longer timeout time.

Also, if your hosting service allows you to do so, you can restart PHP or ask the host to do so, and see if the problem is resolved by the restart.

Controlling the CDN

Another possible solution may be to temporarily disable the CDN, i.e. the Content Delivery Network. In fact, error 502 can occur due to the use of Ddos protection services and firewalls included in third-party CDN networks such as those employed by GoDaddy and CloudFlare.

To give an example, in the case of CloudFlare the 502 bad gateway problem can occur in two distinct forms.

Error 502 Cloudflare

In one case, as in the example above, it depends directly on CloudFlare and so it’s not possible to fix it yourself, unless you contact customer support.

Error 502 Bad Gateway Cloudflare

In the second case, instead, CloudFlare warns you through an error message like the one you see above, that the problem is due to the hosting.

Check plugins and themes in WordPress

In some cases, the use of plugins or themes with wrong configurations can generate the appearance of errors like this one. To solve the 502 bad gateway error in WordPress you can first try to deactivate the plugins you use, to check if they are the ones responsible for the problem. To disable all plugins, you can go to the admin panel, select all of them by clicking on the box at the top and then through the menu of “Group Actions” select the option “Disable”.

502 Bad Gateway Deactivate WordPress Plugins

After deactivating all plugins, to identify which of them causes the error, you will have to reactivate them one by one.

To prevent plugins and other WordPress extensions from causing errors it is important to remember to keep them updated and to check that they do not conflict with your version of PHP.

Conclusion

In this article, we have seen what the 502 bad gateway error means, examined what are the main causes and seen how to fix them.

When did you come across this error: while surfing the web or was it when your website presented such an error? Were you able to fix it by following any of these steps? Did you have to contact your host? Let me know in the comments below.

What is worse than trying to reach a website only to be haunted by a 502 HTTP status code message? It mostly shows up in the form of a Bad Gateway error, but any messages falling under the 5xx spectrum are called HTTP response status code errors indicating that an invalid response was provided by the destination server.

Any error starting with a 502 is always a server-side error, meaning the issue is with the hosting web server. So, before you start scrambling to call your internet provider, let us discuss the various reasons behind its appearance and simple ways to fix it.

Various Flavors of the 502 Status Code Errors

502 Bag Gateway Error

Due to browser variations, operating systems, and the like, a 502 HTTP status code error message may come in different wordings but they all convey the same meaning.

Whether you are a website developer or a web junkie, becoming familiar with this error message can be valuable in diagnosing and fixing website configuration errors and your browsing experience.

Here is a list of common 502 status code variations that you may stumble across:

  • 502 Bad Gateway
  • 502 Service Temporarily Overloaded
  • Error 502
  • Temporary Error (502)
  • 502 Proxy Error
  • 502 Server Error: The server encountered a temporary error and could not complete your request.
  • HTTP 502
  • 502. That’s an error
  • Bad Gateway: The proxy server received an invalid response from an upstream server.
  • HTTP Error 502 — Bad Gateway

Did you know that Twitter’s famous «fail whale» image that declares that Twitter is over capacity is in fact a 502 Bad Gateway error?

Reasons Behind the 502 HTTP Status Code Error

Angry computer user

Communication issues between online servers or DNS issues such as incorrectly cached IP addresses play a big role in the appearance of this annoying error. However, there are a few other culprits at play as well:

The Server Is Inaccessible

This 502 error code is a by-product of a source or origin server being out of order. A range of connectivity issues, a server that is powered down, or spikes in traffic can all lead to this message.

DNS Issues

DNS issues are a major underlying reason behind this error. If the DNS records are misconfigured at the hosting level, the domain name will not resolve to the IP address causing this error to pop up.

Also, keep in mind that most DNS changes take time to propagate and DNS changes have to abide by the TTL (Time To Live) threshold before being implemented. This delay can also generate the 502 Bad Gateway error message.

Blocks and Firewalls

Are you behind a firewall? Depending on the firewall settings, communication between servers can be disrupted and, in some cases, certain websites with security plugins can also block out your local IP address.

Browser Issues

At times, outdated browser versions and certain browser extensions like AdBlock can be the main reason behind the appearance of a 502 error message.

Server Failure

A failed server will most likely generate a 502 error code. Many reasons including system crashes and servers being taken down for maintenance purposes can render servers temporarily useless. In rare cases, a server failure could also happen if the content hosted on a server is in violation of the terms and services set forth by the provider.

Now that you know the reasons behind this status code error, let us explore the ways to fix it.

Ways to Fix The 502 Status Code Error Message

Whether you are a site owner or just surfing the web, the following tips can help keep the pesky 502 error message at bay:

Reload the Website

The fix can be as simple as waiting for a couple of minutes and reloading the website as network congestion issues can sometimes make the server take longer to respond.

Cleare the Browser Cache

Sometimes the 502 error message can appear if the browser is loading the website from the cache. Simply clearing out your browser’s cache can fix this error in most cases. Caching is a great way for speeding up your browsing experience, but it is worth it to clear it from time to time.

Disable the Firewall

A firewall provides an extra sheath of security between your browser and the destination server, but many firewalls are overly sensitive and can block out all inbound requests. If you face the 502 error message, try disabling the firewall or the CDN if you are behind one.

If the error disappears after disabling it, then that means your firewall was the main culprit.

Update the Themes and Plugins

Website and browser plugins can sometimes cause the 502 status code error as well. Simply disable all the plugins. If this resolves the error message, then activate each plugin one by one until you catch the one that was generating the error.

If you are hosting a website and disabling the plugins does not help, then try updating your website theme. Many websites hosted on platforms like WordPress or Wix need regular theme updates to function properly.

Check With the Provider

If your website is still generating a 502 error code even after trying the previous tips, then it is worth reaching out to your hosting server. Most hosting providers have customer support teams that can triage the issue with you.

The Bottom Line on the 502 HTTP Status Code Error

A 502 error can be quite aggravating as it can be caused by an assortment of issues. Troubleshooting the 502 Bad Gateway error takes a lot of effort, but with a little bit of patience, and the guidelines provided in this article, you should be able to resolve it in no time.

So, what are you waiting for? Put your techie glasses on and start troubleshooting the pesky 502 and other website error messages!

Jan 05, 2023

Nabilla R.

9min Read

The reasons for 502 bad errors can be numerous, from minor browser-related issues to problems with CDNs. This article will go over some troubleshooting steps to follow when a 502 Bad Gateway error occurs, both for the server and client-side. We will also take a look at the different factors that might cause this error message, along with the impact they can have on your site’s SEO.

Error code 502 Bad Gateway Error
Error type Server-side error
Error variations Temporary Error (502)
HTTP Error 502 Bad Gateway
502 Proxy Error
Bad 502 Gateway
502 Service Temporarily Overloaded
A blank white screen
Error causes Unresolved domain name
Server overload
Browser issues
Home-network equipment error
Firewall blocks

502 Bad Gateway Error – Video Tutorial

Looking for an easy visual guide? Check the video below.

youtube channel logo

Subscribe For more educational videos!
Hostinger Academy

What Is a 502 Bad Gateway Error?

The 502 Bad Gateway error indicates that the server which you’re connecting to received an invalid response. When accessing a URL, your browser sends an HTTP request to the server, which in this case was invalid, returning an HTTP 502 status code.

Browsers and servers interact with each other using HTTP (HyperText Transfer Protocol) status codes. Whenever you access a URL, the browser sends an HTTP request to the webserver of the site you’re accessing. The server then returns a status code along with the resources you requested.

HTTP status codes are grouped into five server responses:

  • 1xx – informational
  • 2xx – success
  • 3xx – redirection
  • 4xx – client error
  • 5xx – server error

A graphical illustration showing how a 502 bad gateway occurs.

An HTTP status code starting with the digit “5” relates to errors that occur when there’s a network error or communication problem between web servers.

Other 5xx status codes include the 500 Internal Server Error, 501 Not Implemented, 503 Service Unavailable, and 504 Gateway Timeout. Though the exact reasons for each error vary, in most cases, the cause lies within the server. 

What Causes a 502 Bad Gateway Error?

Before you can fix the Gateway error, you need to examine the potential factors causing this error, such as:

  • Unresolved domain name. This happens when a domain name is not resolving to the correct IP. Keep in mind that if you have recently migrated your domain name to another host, DNS servers changes might take up to 24 hours to be fully propagated and active.
  • Origin server overload. Whenever an origin server runs out of resources, it can get overloaded and crash, triggering an http error 502. A sudden spike of traffic, low memory, and software timeouts are some of the common reasons for server overload. 
  • Browser errors. Sometimes, a browser might show a 502 coding error despite not having server or network issues. In this case, the error might be triggered by faulty browser extensions such as ad-blockers, outdated browser versions, or corrupted files in your browser cache.
  • Home-network equipment issues. If you encounter HTTP 502 Errors in more than one website or browser, there is a good chance that your network equipment might be having a temporary connection problem. 
  • Firewall blocks. A firewall protects your website from any suspicious traffic. However, some firewall systems are over-sensitive and might detect false positives. The system might be blocking a specific ISP or a request from a CDN.

How to Fix 502 Bad Gateway Error

Although the 502 Bad Gateway error usually relates to server-side problems, it can also be caused by misconfigurations or temporary issues from the client-side. Hence, we’ll overview the common troubleshooting steps with both causes in mind. 

While some solutions are focused on WordPress, most of them can be applied to any website. 

1. Refresh the Page

The first solution is a fairly simple one – wait around for a minute or two and refresh the web page you’re on. In a lot of cases, the error comes from a sudden traffic surge.

Thus, a simple page refresh usually will do the trick. For a shortcut, Windows users can press F5 or CTRL + F5, while Mac users can press CMD + R

You can also try checking if the website is offline using an online tool, such as Website Planet or Host Tracker. This will help identify whether a server or a client-side issue causes the error.

2. Clear Browser Cache

If the error persists, there is a chance that your browser cache has saved outdated and corrupted files. In this case, clearing the browser cache can fix an HTTP 502 Bad Gateway error.

Keep in mind that removing cached files might risk you losing important browser data, including bookmarks and setting preferences. To prevent this, simply export your data from the browser and import it back after.

3. Try in Incognito Mode

Accessing the website using Incognito mode is also a good idea as it helps determine whether the HTTP Error 502 message appears due to a browser-related issue. To open an Incognito window, click on the three-dots button on your browser screen and choose New Incognito Window.

Open incognito mode from browser

If the error doesn’t occur in Incognito mode, the problem might be caused by a browser extension. 

With that in mind, try to disable your add-ons or extensions gradually. Once you delete the one causing the error, you should be able to access the website.

If disabling extensions doesn’t help, try opening a new browser session. For example, if you’re currently on Google Chrome, try using Mozilla Firefox.

When the page loads normally on the new browser, your previous browser might be causing the error. To solve the problem, try deleting and reinstalling your faulty browser.

4. Flush DNS Servers

The error can also occur due to DNS problems, such as incorrect IP addresses and unresponsive DNS servers. 

In this case, flushing your DNS cache can be the answer. This method works similarly to clearing your browser’s cache. It will remove faulty files from your DNS server.

Temporarily changing your DNS servers is another step you can take. By default, your DNS servers are assigned by your ISP. However, you can always change it to a third-party server, such as Google Public DNS.

5. Test on Another Device

If none of the above solutions fixed the HTTP error 502, test the connection on another computer or a mobile device, preferably connected to a different network. 

Try restarting your PC and other networking equipment. To do so, turn off your computer and unplug your wireless router. Wait for a moment and plug them back on.

This step helps decide whether the error is related to your networking equipment or if the problem lies elsewhere.

6. Check Error Log

When you experience an error after a particular change or update, the fault may lie within your server itself. The best approach to this issue is to check your website error log.

Usually, your hosting service gives access to enable website error log through an admin dashboard. You can also enable error logging on your WordPress site by adding the following lines in wp-config.php:

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

All of the generated errors will appear in the wp-contents/debug.log file, allowing you to detect which ones are causing a 502 Bad Gateway error.

7. Check Plugins and Themes

Sometimes, faulty plugins or themes can be one of the reasons for the error. 

This is because poorly coded plugins and themes can conflict with each other. When this happens, your server will stop every script and query on your website, making it inaccessible.

For some websites, the issue usually comes from caching or security plugins. There is a good chance that these plugins block communication between servers, causing the error to persist.

If you don’t have a caching or security plugin installed but still encounter an HTTP 502 Error, it’s best to disable your plugins and re-activate them one by one. To do so, go to Plugins and simply click Deactivate from the Bulk Actions menu.

Wordpress dashboard deactivating plugins

Then, activate each plugin while refreshing your WordPress site after each one. Once the 502 Error pops up again, you have found the problem plugin.

However, if you can’t access your WordPress dashboard, you can try disabling them from your hosting panel or FTP program. Navigate to the wp-content directory and rename the plugins directory, for example, plugins-disable.

If you use Hostinger, access your hPanel and click on Files. From there, go to File Manager -> public_html -> wp-content. 

Disabling all WordPress plugins via FTP

Once your site starts working after all plugins are disabled, you may rename the folder back to plugins. Then try enabling the plugins one by one to determine which one caused the error in the first place.

If the website still doesn’t work, follow the same steps with your WordPress themes.

8. Check CDNs

Another cause of the 502 Bad Gateway errors can be problems with your CDN or DDoS mitigation services. 

A content delivery network adds an extra layer between your server and browser to efficiently deliver web content. However, this layer can run into an issue when connecting with your origin server, resulting in 502 Errors.

One notable example would be Cloudflare, where the 502 Bad Gateway can occur in two different variations depending on the issue.

Cloudflare 502 error

The screen above indicates that the issue is on Cloudflare’s side. To fix it, you’ll need to reach out to their customer support team. Remember to check the Cloudflare System Status page before doing so.  

Alternatively, you may choose to disable Cloudflare, though keep in mind that your DNS propagation may take a couple of hours.

502 bad gateway error

However, if you see the Cloudflare error shown above, it means that the issue lies with your current hosting provider. In this case, try to contact your web host support team and ask for assistance.

9. Check the Site Status

If the 502 Error code is still showing up despite trying most of the methods so far, it is possible the origin server might be currently experiencing a downtime.

Luckily, there are many tools on the web to examine if a site is down, including Down for Everyone or Just Me and IsItDown. Simply input your URL and check the status of your website.

10. PHP max_execution_time and max_input_time

PHP timeout happens whenever a PHP process loads for more than the specified max_execution_time or max_input_time. These are the values set in your PHP configurations on your web server. Usually, the values are set to 300 seconds by default.

A timeout can happen during the migration process and trigger a 502 Bad Gateway error. To fix this issue, you can talk to your web host to check what your values are set at and if you can increase them. 

11. Contact Customer Support

If none of the above solutions fixed the error, it’s best to contact the customer support team. 

While describing the issue, try to include what troubleshooting steps you have taken. Provide as much information as possible, and let the support team assist you.

502 Bad Gateway Error Variations

The error can appear on any browser, operating system, and service. However, its appearance varies in different ways. Here are some alternatives that you might encounter on the web:

  • Temporary Error (502)
  • 502 Error
  • Error 502
  • HTTP Error 502 Bad Gateway
  • 502 Server Error: The server encountered a temporary error and could not complete your request
  • 502 – Web server received an invalid response while acting as a gateway or proxy server
  • HTTP 502
  • 502 Proxy Error
  • Bad 502 Gateway
  • 502 Service Temporarily Overloaded
  • 502 Bad Gateway Nginx
  • A blank white screen

Keep in mind that some websites or services have custom 502 Error pages and will look different, for example:

Chrome

Google chrome 502 error

Chrome’s 502 Bad Gateway error screen tells you that the server encountered a temporary error and could not complete your request. Chrome also suggests trying it again in 30 seconds. If the problem continues, try accessing the site from different browser windows.

GitLab

Gitlab 502 error

GitLab serves a 502 Bad Gateway error when its reverse proxy server doesn’t receive a response from GitLab’s origin server for an extended period. The error page also displays instructions to solve the issue.

Twitter

Twitter 502 error

Twitter has its own way of displaying a 502 service temporarily overloaded error. It incorporates a playful illustration with a clear-cut message. Users can also check out the Twitter Status page for real-time data statistics.

How 502 Bad Gateway Error Affects SEO

A 502 Error code appears when your server experiences a networking error that prevents it from completing a request. If this error keeps happening regularly and for an extended period of time, it can have a negative impact on your website SEO. 

When a requested page is not served, visitors will be more likely to leave your site, resulting in a poor user experience. Moreover, the longer your site is unavailable, the higher your bounce rate will be.

Similar to human visitors, search engine crawlers also see a page with a 502 Error as broken, which prevents them from indexing and ranking the page. 

With that in mind, it is crucial to investigate the factors causing the error and fix it as soon as possible for the sake of SEO.

Error Status Codes Similar to 502 Bad Gateway

Understanding error codes are important for website owners and developers to identify and fix the problem quickly. Aside from HTTP 502 Errors, there are other status error codes that your website may encounter. 

The most common ones include:

  • 403 Forbidden Error. Occurs when the webserver restricts visitors from accessing specific content. 
  • 404 Page Not Found. Refers to a response sent whenever the requested web page is not available.
  • 501 Not Implemented. This indicates that the server doesn’t have the functionality to fulfill a certain request.
  • 503 Service Unavailable. This shows that the server is currently down due to maintenance and fails to process the request.
  • 504 Gateway Timeout. Appears as a result of proxy error when one waits too long for a response from the upstream server.

Conclusion

A 502 Bad Gateway happens when a server that functions as a gateway receives an invalid response from the origin server. If left untreated, this error will impact your conversion rate, the user experience, and page rankings.

As the status code suggests, the root of this error usually lies on the server-side. In other words, the problem doesn’t come from your website, internet connection, or computer. With that in mind, it is also important to keep an eye out for broken plugins or themes.

We hope these troubleshooting steps help you remove any errors you might run into and return your site to a stable condition. If you have any extra tips or solutions, feel free to share them with us in the comments below.

502 Bad Gateway FAQ

Why Do I Get a 502 Bad Gateway Error?

502 Bad Gateaway Error is a generic error indicating that something is not quite right with the website’s server communication. It won’t tell you exactly what’s wrong, though.

Is 502 Bad Gateway a Virus?

502 Bad Gateaway Error is not a virus – it’s an error message that is often the result of issues with communication with a website’s server.

Author

Nabilla is a website hosting and development enthusiast. She loves to share her knowledge with others in order to help them grow their online presence. When she’s not busy writing, Nabilla enjoys exploring nature and going on adventures. She is passionate about helping people achieve their online goals.

Everything doesn’t always run smoothly when surfing the net. Now and again, you’ll visit a website and instead be greeted by an HTTP status code. Something went wrong! If you run up against a 500 code as an internet user, then in most cases the problem is not with you or your internet connection — it’s far more likely that it’s the website’s server instead. With a 502 error, though, it can occasionally happen that something is wrong with your settings — especially if you’re suddenly receiving the annoying status code regardless of which sites you’re trying to access. This article gives you tips on how to suss out the source of the error and what you can do as a user to once again view the content of the website. Or are you the operator of an affected website? We’ll tell you how to check for that error too.

Contents

  1. What does ‘bad gateway’ mean?
  2. What are the sources of the 502 Bad Gateway error?
  3. Fixing the 502 error
    1. As an internet user: Fix 502 or bypass it
    2. As a webmaster: Examine the website

What does ‘bad gateway’ mean?

The internet protocol HTTP generally provides status codes in response to queries. The most common code is probably number 200: OK. Everything has worked as it should. This status isn’t usually shown to users, though. Instead, visitors simply see the requested website content. On the flip side are the error messages: While 400 codes imply that the error lies on the client side, 500 to 511 codes mean that the negative result is the server’s fault. The status codes also indicate where the error occurred — at least to users who know what the individual codes mean.

The 502 error is usually provided with the addition Bad Gateway or as a “502 Bad Gateway Nginx”, “502 Bad Gateway Apache”, or “502 Bad Gateway registered endpoint failed to handle the request” message. Next to the well-known 404 error (“Page not found”), the bad gateway error is one of the most common error messages received when surfing the internet. It’s delivered when the server, which is accessed via the main server, couldn’t forward the request. In this case, the first server functions only as a proxy or gateway. In principle, all queries on the internet are forwarded via gateways. That’s why this error message is often so frustrating: It’s generally not at all clear at which point in the process the request encounters the error.

What are the sources of the 502 Bad Gateway error?

In most cases, the bad gateway error occurs on the server side and can’t be fixed by the internet user. But it’s also possible that the browser being used has registered a 502 error where really none exists. It’s also possible that you’re disconnected from your network. The following reasons could explain why the infamous HTTP code is displayed:

  • Server failure: The gateway receives a negative result if the target server has failed completely, among other things. This can occur due to a system crash. In rare cases, servers can also be taken offline spontaneously — for example, when the content is in violation of a law.
  • Webserver overload: If a webserver reaches its limit, it can’t answer any more requests — the gateway then delivers the status code 502 Bad Gateway. The reason could be an unexpectedly high interest in the site or even a DDoS attack. This means that an attacker is using a bot network to help overload the server capacity and provoke a system failure.
  • Faulty PHP programming: Occasionally, there’s an error in the website’s code. Certain requests will then not be answered correctly anymore, delivering a negative result instead.
  • Communication error: Firewalls can cause errors on both sides of the communication (server and client) with the forwarding of requests.
  • Browser error: Browser extensions can also sometimes cause errors with the display of a website and generate a 502 error.

Fixing the 502 error

Internet users, as well as webmasters, have the ability to respond to a bad gateway situation. In many cases, just waiting for a little while is enough. Often, the error occurs outside of your sphere of influence and is solved by the internet provider (ISP) or the hosting provider of the web server without any intervention on your part. But sometimes the error is on your side, so you should know where to begin to search for the cause.

As an internet user: Fix 502 or bypass it

If you want to access a page and instead get the status code 502, there’s a high chance that the error isn’t with you. In most cases, it can be fixed by simply reloading the page. If the problem is solved by doing that, then it means that the server was just temporarily overloaded. Since such failures can also last for a fairly long time, reloading the page again is only really worth it after 15 minutes. Still receiving the same error message? Then clear your cache and cookies, as it could be that your browser didn’t truly reload the page and instead just accessed data from your internal storage (you don’t necessarily have to delete all of your cookies. Within your browser, you can display all of the cookies and remove only those that have something to do with the corresponding website.)

If the error is actually on the server side but you still want to access the content right away, there are also other ways to bypass the error message. This relies on the Google cache. Google saves websites for a time on its own servers and so can display an earlier version of the respective website. To load the cache page of the search engine, enter cache: in the search field and then the URL that you would like to visit (for example, cache:https://facebook.com). You should be aware, though, that you’re viewing an outdated version of the site. If you need to go back through the site’s history to find a working version, then the Wayback machine — from the nonprofit internet archive — can help. Various versions from the past years are stored here.

Information panel of the Google cache

If you load a website from the Google cache, it provides a panel to inform you of when the copy was created.

The error could also be in your system — even if the status code indicates something else. To check whether the error stems from other users or you, you can, for example, use the web service Down for everyone or just me?. Of course, if you can’t access any websites without the “Bad Gateway” message, then it’s obvious that the error has something to do with your computer, browser, or firewall. If the error is actually only occurring for you, then check the functionality of your browser. The first step should be restarting the browser. If this doesn’t work, then start your browser in safe mode. In safe mode, the browser deactivates any installed plugins. This allows you to check if a browser extension is the source of the error message.

To do this, you need to open the command line of your operating system (for Windows, this is the Command Prompt, for Mac, the terminal). First, locate the file to run the browser, and then type the complete path in quotation marks in the command line. Every browser manufacturer has a different command for starting the safe mode:

  • Firefox: “C:Program FilesMozilla Firefoxfirefox.exe” -safe-mode
  • Internet Explorer: “C:Program FilesInternet Exploreriexplore.exe” -extoff
  • Chrome: Google’s browser doesn’t offer a safe mode. If you instead switch to incognito, all extensions will be deactivated.

Command Prompt for starting Firefox and Internet Explorer in safe mode

Check which path contains the file to start the browser

You can also use something other than your standard browser. If this is successful, then it’s recommended to uninstall and reinstall your current standard browser. If switching browsers doesn’t solve the problem with the bad gateway error, then it’s time to check your network settings. The simplest option here is to restart your modem and router. If this isn’t successful, then try to switch from Wi-Fi to LAN and use a cable connection.

Sometimes, the error isn’t with you or the website operator, but instead the “502 Bad Gateway” error is the internet provider’s fault. The cause would then be a false entry on their DNS server. To bypass the error message, enter a different DNS server into your settings. On Windows, this can be changed in your TCP/IP connection settings. For testing purposes, you can access Google’s free DNS server, for example, at 8.8.8.8 and 8.8.4.4.

If the error isn’t caused by the webmaster, there’s not much left for you to do other than wait (or use a cached version). In most cases, the error is temporary and is already being tackled by the webmaster. For smaller sites, it could also be helpful to take the initiative and contact the operator of the website. It could be that they don’t know about the disruption yet and will appreciate your heads-up.

As a webmaster: Examine the website

A visitor to your website has shared with you that they’re seeing the error message 502 when they try to access your website. What does that mean for you? Just as for the surfing visitor, it’s not always clear to the webmaster at first glance where the error lies. First, you need to check whether your website is still accessible in general. If your server is truly failing, you should contact your hosting provider. Maybe they already know about the error and their IT team is working on a solution. You should also check the log files of your server for error messages. PHP programming in particular can often be the source of errors, so definitely check if your error source is either there or in your database. If necessary, you could use an old backup to quickly remedy the failure.

 Oftentimes, the error only occurs because the server was temporarily overloaded or took too long to provide a response to the upstream server. If such overloads start occurring more frequently, you should contact your hosting provider. Together, you can achieve a better configuration for your webserver so that it doesn’t fall to its knees at peak times. But in some cases, it’s the communication between the different webservers that isn’t running smoothly. Then you should check whether your firewall is correctly set up and make sure that it’s not blocking any legitimate queries. Another source of error could be that the name resolution isn’t functioning properly. Check your name server settings with your hosting provider (for IONOS users, this takes place via the customer login. There you need to select the appropriate domain and switch to DNS settings).

Tip

If you should encounter a server failure that you can’t fix within a few minutes, then you should be sure to use your social media channels to inform the visitors of your website.

Related articles

What is a CDN (Content Delivery Network)?

What is a CDN (content delivery network)?

If your online project is growing and beginning to attract international customers, the workload of your server is also increasing. High user numbers and the large geographical distribution of the clients result in ever-increasing loading times and slow transfer rates. By using a CDN (content delivery network), you’ll be able to react to increasing demands and optimize your data delivery.

What is a CDN (content delivery network)?

Index management with the robots.txt file

Index management with robots.txt files

With the file, robots.txt, website operators are able to greatly influence which portions of their web projects are able to be read by search bots. In addition to HTML meta tags, redirects, and canonical tags, this seemingly insignificant text file located in the domain’s root directory is an important tool for index management. We’ve laid out how robot.txt files are built and what website…

Index management with robots.txt files

What does the'404 Not Found' error mean?

What ‘Error 404’ means and how to fix it

How often have you stumbled upon a dead end while surfing the net? HTTP 404 error pages are commonplace online to inform users that the requested page isn’t available. As well as being annoying for visitors, they spell bad news for website owners since a dead link may have a bad influence on a website’s search engine ranking. In this article, we’ll demonstrate the importance of 404 pages and…

What ‘Error 404’ means and how to fix it

HTTP 400 Bad Request | finding the causes

HTTP 400: Bad Request explained

Internet users are often confronted with error messages. HTTP status codes can be especially annoying, and even more so if you don’t understand what they mean. The message ‘HTTP 400 – Bad Request’ is a mystery for many internet users, but luckily it can be solved in most cases. We explain what the error message means and how to fix the error.

HTTP 400: Bad Request explained

Инструкции для пользователей и для администраторов сайтов.

Что такое ошибка 502 и как её исправить

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

Ошибка 502 Bad Gateway указывает, что сервер, с которым пытался соединиться ваш компьютер или смартфон, получил неверный ответ сервера уровнем выше. Чаще всего это происходит из‑за проблем в работе DNS, прокси или хостинга.

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

Идите от простого к сложному — и в какой‑то момент ошибка, возможно, исчезнет.

Проверьте подключение к интернету

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

Посмотрите, у всех ли отображается ошибка 502

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

Если другого гаджета под рукой нет, можно воспользоваться онлайн‑сервисами. Они покажут, доступен ли сайт у других пользователей:

  • Down for Everyone or Just Me;
  • Is It Down Right Now;
  • Reg.ru;
  • 2IP.

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

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

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

Попробуйте другой браузер

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

Отключите плагины и расширения в браузере

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

Очистите кеш браузера

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

Вот как это сделать в Chrome.

  1. В настройках перейдите к разделу «Конфиденциальность и безопасность» и выберите пункт «Очистить историю».
  2. Поставьте галочки напротив второго и третьего пунктов: «Файлы cookie и другие данные сайтов», «Изображения и другие файлы, сохранённые в кеше».
  3. Затем нажмите «Удалить данные».

Инструкции для остальных браузеров ищите здесь.

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

В Windows 10

  • Чтобы вызвать консоль, напишите cmd в окне поиска меню «Пуск».
  • В открывшемся окне введите команду ipconfig /flushdns и нажмите Enter.

В Windows 7

  • В консоли введите команду ipconfig /flushdns и нажмите Enter.
  • Затем там же выполните команды net stop dnscache и net start dnscache, чтобы перезапустить службу DNS‑клиента.

В macOS

  • Нажмите на иконку поиска в правом верхнем углу и напишите «Терминал».
  • В открывшемся окне терминала введите команду sudo killall -HUP mDNSResponder; sleep 2;.

В Linux

  • Запустите терминал сочетанием клавиш Ctrl + Alt + T или из основного меню.
  • В открывшемся окне введите команду sudo service network‑manager restart и нажмите Enter. Это точно работает на Ubuntu и иногда на других дистрибутивах. Альтернатива — команды sudo systemd‑resolve —flush‑caches или sudo /etc/init.d/nscd restart.

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

Перезагрузите роутер

Зайдите в консоль управления маршрутизатором и найдите соответствующий пункт. Или отключите питание устройства на 10–15 секунд, а затем снова подключите его к электросети.

Измените DNS‑сервер по умолчанию

В настройках роутера укажите адреса публичных DNS‑серверов. Например, можно вписать IPv4 для Google Public DNS: 8.8.8.8 или 8.8.4.4. Или, если ваш сервер поддерживает IPv6, задайте адреса 2001:4860:4860::8888 и/или 2001:4860:4860::8844.

Зайдите позднее

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

Сообщите администратору

Если у вас есть контакты администратора сайта, расскажите ему об ошибке 502. Возможно, он ещё не в курсе проблемы и, соответственно, пока не решает её.

Как администратору исправить ошибку 502

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

Проверьте журнал ошибок

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

Отключите или удалите свежие плагины и компоненты

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

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

Попробуйте отключить анти‑DDoS

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

Но если в этой цепочке что‑то идёт не так, возникает ошибка 502. Попробуйте временно отключить анти‑DDoS — иногда после этого проблема исчезает.

Увеличьте количество ресурсов

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

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

Попросите помощи

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

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

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

Читайте также 💿⚙️💻

  • Что делать, если тормозит браузер
  • Как исправить ошибку CPU Fan Error при загрузке компьютера
  • Что делать, если DNS-сервер не отвечает
  • Что такое ошибка 500 и как её исправить
  • Что означает 404 Not Found и другие ошибки веб-страниц

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

Ошибка 502 Bad Gateway: что значит

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

Ошибка 502 Bad Gateway возникает при неправильной работе прокси-сервера, DNS-сервера и чаще всего сервера, на котором размещён сайт. Проблема может распространяться как на весь ресурс, так и на отдельные страницы. Это зависит от характера проблемы. Существуют разновидности 502 ошибки: Bad Gateway Nginx, Bad Gateway Apache. Об их отличиях мы расскажем ниже. Также эта ошибка может иметь формулировки:

  • Bad Gateway: Registered endpoint failed to handle the request, Temporary Error (502),
  • Error 502,
  • Bad 502 Gateway,
  • 502 Error,
  • 502. That’s an error,
  • 502 Service Temporarily Overloaded,
  • 502 Server Error: The server encountered a temporary error and could not complete your request,
  • 502 – Web server received an invalid response while acting as a gateway or proxy server,
  • 502 Bad Gateway Nginx,
  • 502 Proxy Error,
  • HTTP 502,
  • HTTP Error 502 Bad Gateway.


Что значит плохой шлюз: ошибка 502

Причины возникновения ошибки 502 Bad Gateway

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

  2. Большое количество посетителей одновременно. Веб-ресурс может посещать ограниченное количество посетителей. Сколько человек может посетить сайт зависит от возможностей сервера (размера оперативной памяти) и настроек, которые сделал создатель ресурса. Если по какой-либо причине на сайт зайдёт больше пользователей, чем запланировано, сервис может не справиться и страница выдаст код 502. Такое случается при рекламных акциях и распродажах в интернет-магазинах.
  3. Атака хакеров или DDoS-атака. Эта проблема связана с предыдущей причиной перегрузки. Хакер имитирует большой наплыв пользователей, из-за чего сервер выходит из строя. Такие атаки могут быть использованы для снижения продаж.
  4. Плохая оптимизация сайта. Настройки ресурса сделаны так, что маленькое количество посетителей генерирует много запросов. В этом случае нужно оптимизировать работу сервера с пользовательскими запросами.
  5. Второй причиной возникновения кода 502 могут явиться ошибки РНР. Если для расширения функционала сайта в панель управления были добавлены некорректно настроенные плагины, они могут выдавать проблемы в своей работе. Вместе с ними ошибку покажет и сайт целиком. Также если код сайта написан неправильно, запросы могут давать отрицательный результат.
  6. Ошибка браузера. Проблема может быть на стороне пользователя, если у него установлены расширения, которые нарушают соединение с сервером сайта.

Чем отличается ошибка 502 Bad Gateway Nginx

Между браузером и сервером может стоять веб-сервер. Он используется для снижения нагрузки на сервер, аутентификации пользователей и многого другого. Самые популярные программы для создания веб-сервера ― Nginx и Apache. Так как веб-сервер является посредником между браузером и сервером, то именно он будет оповещать пользователя о проблеме. Поэтому в зависимости от веб-сервера в сообщении вы можете увидеть надпись Bad Gateway Nginx или Bad Gateway Apache. При этом причины возникновения проблемы одинаковы.

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

Что делать, если вы пользователь

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


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

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

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

ipconfig /flushdns

  1. Дождитесь сообщения об очистке кэша:
  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. Попробуйте заново зайти на сайт.

Что делать, если вы владелец сайта

Проверьте количество свободной памяти. Это можно сделать двумя способами.

Способ 1 ― введите команду top в командной строке сервера:

Mem ― вся оперативная память.

Swap ― раздел подкачки.

Посмотрите на строку Memfree. Это количество свободного места на сервере. Если там указано маленькое число, ошибка 502 Bad Gateway появляется из-за нехватки памяти. Увеличьте количество оперативной памяти и проблема пропадёт. Также в результатах можно будет увидеть, какую нагрузку на сервер даёт каждый отдельный процесс.

Способ 2 ― введите команду free -m.

Mem ― вся оперативная память.

Swap ― раздел подкачки.

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

Проверьте логи сервера. Если проблема возникла в момент каких-либо обновлений на сайте, проверьте журнал изменений, чтобы отменить те доработки, которые нарушили функциональность сервера. Также в логах можно увидеть DDos-атаку. Если дело в нехватке памяти, в логах отобразится ошибка OOM (out of memory).

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

  1. 1.

    Войдите в панель управления WordPress. Если вы пользуетесь услугой REG.Site, войти в панель управления CMS можно прямо из Личного кабинета.

  2. 2.

    Перейдите во вкладку «Плагины» ― «Установленные».

  3. 3.

    Нажмите Деактивировать у плагина, который, как вам кажется, повлиял на работу сайта:

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

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

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


Сайт находится на виртуальном хостинге REG.RU

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

  1. Точное московское время наблюдения проблемы.
  2. Название сайта, на котором была замечена проблема.
  3. Если ошибка отображается не сразу, а после определённых действий (добавление изображения, отправка формы с сайта, импорт файлов), подробно опишите порядок действий, по которому мы сможем воспроизвести проблему.
  4. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.


Сайт находится на VPS REG.RU

Чаще всего на VPS используется связка: Nginx + бэкенд-сервер (Apache, PHP-FPM, Gunicorn, NodeJS). Ошибка 502 возникает в случае, если Nginx не может получить ответ от этих сервисов.
Клиенты с VPS сталкиваются с «502 Bad Gateway», когда:

  • какой-то из сервисов выключен. Перезапустите веб-сервер Apache, PHP-FPM либо другой сервис, с которым работает Nginx;
  • между Nginx и бэкенд-сервером некорректно настроена связь. Например, Nginx производит обращение к порту 8080, а веб-сервер Apache «слушает» на 8081. В этом случае необходимо скорректировать настройки веб-сервера.

Если вам не удалось самостоятельно устранить ошибку 502, обратитесь в техподдержку. В заявке укажите:

  1. Точное московское время наблюдения проблемы.
  2. Название сайта, на котором была замечена проблема.
  3. Если ошибка отображается не сразу, а после определённых действий (добавление изображения, отправка формы с сайта, импорт файлов), подробно опишите порядок действий, по которому мы сможем воспроизвести проблему.
  4. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.

502 Bad Gateway Error: What It Is and How to Fix It

Feb 28, 2022 9:59:01 AM |
502 Bad Gateway Error: What It Is and How to Fix It

An in-depth explanation of what a 502 Bad Gateway Error is, including troubleshooting tips to help you resolve this error.

HTTP response codes, particularly those representing an error, can be challenging to deal with. While some are simple, others have obtuse or confusing meanings. These codes result from a much broader relationship between the client, the web application, a web server, and untold numbers of outside web services. As you can imagine, pinning down exactly what a given error indicates can be a challenge in the best of circumstances.

In this article, we’ll explore the 502 Bad Gateway Error, which indicates that a server somewhere within the server stack — specifically, one which is acting as a gateway or proxy itself — received an invalid response from a different server. The problem is another server upstream, meaning that this server provides service to the system you received the 502 Error from. To help you resolve such errors, here are some troubleshooting tips and potential fixes for common causes. Let’s get going!

The Problem is Server-Side

Before we begin, it’s worth noting that, like most HTTP response codes, the 502 Error indicates  that something has gone wrong within the server of your application, as opposed to the client-side of things. If you’re trying to diagnose an issue with your application, you can immediately ignore most client-side code and components. This includes HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. This doesn’t apply solely to websites, either. 

Behind the scenes, normal web applications will power modern-looking smartphone apps. If you’re using such an application and a 502 Bad Gateway Error occurs, the issue will not be related to the app installation on your phone or local testing device. Instead, it will be something on the server-side, which performs most of the logic and processing behind the scenes.

Diagnosing a 502 Bad Gateway Error

As mentioned, a 502 Bad Gateway Error means the client is having difficulty connecting to a server. This means that the server creating the 502 Error is acting as a gateway. Let’s take a moment to discuss what a gateway (or proxy) is. 

A client will connect to a server via a third-party gateway computer in most HTTP communications. The gateway acts as, well, a gateway, where the client sends messages securely to the server and vice-versa. A gateway acts as a node within the larger network web, connecting and routing communications between multiple clients, servers, and other node types within the (virtual) vicinity.

Believe it or not, most homes with Internet access have an active gateway. Your local home network, which is likely set up through a router (or router+modem hybrid), typically assigns IP addresses to all the devices on your network using the base address of 192.168.1.*, where the asterisk changes depending on the device. 

In most cases, the router allows communication from one local network address to another local network address. But when your computer attempts to connect to an IP address outside of this base range, your router’s gateway will intercept. Once intercepted, your router will perform the communication between your computer and the remote server.

Perform a Thorough Application Backup

As with anything, it’s better to be safe than sorry. As such, it is critical that you perform a complete backup of your application and database before attempting any fixes. Create a complete copy of the application onto a secondary staging server that isn’t «live.» This will give you a clean testing ground to test fixes without threatening the security of your live application.

Debugging Common Platforms

If a common software package is throwing a 502 Bad Gateway Error, look into the stability of those platforms first. The most common content management systems (CMS) — like WordPress, Joomla!, and Drupal — are well-tested out of the box. Once you start making modifications to the underlying extensions or PHP code (the language in which nearly all modern content management systems are written), it’s easy to cause an unforeseen issue that results in a 502 Error.

Here are a few tips to help you troubleshoot some of these popular software platforms:

Rollback Recent Upgrades

If you recently updated your CMS before the bad gateway error appeared, consider rolling back to the previous version. Similarly, recently upgraded extensions or modules can also cause server-side issues. 

For assistance, simply Google «downgrade [PLATFORM_NAME]» and follow along. However, certain CMSs won’t provide a version downgrade capability, which indicates that they consider the base application, along with each new version released, to be extremely stable and bug-free. This is typically the case for more popular platforms.

Uninstall New Extensions, Modules, or Plugins

Depending on the CMS, the names of these components will be different, but they serve the same purpose. Extensions help improve the capabilities and features of the platform beyond what it’s normally capable of out of the box. Be warned: these extensions can take full control of the system and make virtually any changes. For example, extensions can change PHP code, HTML, CSS, JavaScript, or the database. If you’re seeing a 502 Bad Gateway Error, try uninstalling any new extensions.

Check for Unexpected Database Changes

It’s worth noting that, even if you uninstall an extension, this doesn’t guarantee that changes made by the extension will be fully reverted. There are scenarios where an extension may modify database records that don’t «belong» to the extension itself. The extension may not know how to revert alterations to database records and ignore such things during uninstallation. 

Diagnosing these problems can be tricky. Your best course of action is to open the database and look for records likely modified by the extension.

Confirm Proper File Permissions

If the application was working fine before and suddenly an error 502 occurs, permissions are probably not the culprit. However, if modifications were recently made (such as upgrades or installations), it’s possible that file permissions were changed. Check out the permissions settings for your application and see if they might be the cause of the 502 Error. 

Above all, Google is your friend. Search specific terms related to your issue, such as the name of your application’s CMS, along with the 502 Bad Gateway Error. Chances are you’ll find someone who has experienced this issue and has shared a solution.

Above all, Google is your friend. Search for specific terms related to your issue, such as the name of your CMS, along with the 502 Bad Gateway Error. Chances are you’ll find someone who has experienced this issue and has a solution.

Troubleshooting on the Server-Side

If you aren’t running a CMS application or you know that the 502 Bad Gateway Error isn’t related to your CMS, here are some additional tips to help you troubleshoot what might be causing the issue on the server-side of things:

Recent DNS Changes

The Domain Name System (DNS) is a decentralized naming system for devices connected through a network. In short, the DNS associates domain names (e.g. airbrake.io) to specific IP addresses. It then stores that association in a series of authoritative name servers spread around the world. 

When you ask your computer to connect to airbrake.io, your computer actually checks with a nearby DNS name server to find and connect to a specific IP address. The traffic is routed to an IP address (52.203.232.56, in this case). 

Recent changes to your DNS server could result in a 502 Error. Such DNS changes, known as DNS propagation, are not instant and can sometimes take a few hours to propagate. 

Server Connectivity Issues

It’s entirely possible that a 502 Error indicates that a server somewhere in the chain is down. Most modern applications don’t reside on a single server. Instead, they may be spread over multiple systems, or even rely on many third-party services to function. If any one of these servers is down for maintenance or inaccessible, this could result in an error that appears to be from your own application.

Improper Firewall Configuration 

A firewall is a basic security device that monitors network traffic and acts as a gatekeeper, deciding which traffic is safe and which could be malicious. However, automatic firewall services can sometimes mistake perfectly safe and valid content from content delivery networks (CDNs) or elsewhere as malicious. When that happens, your firewall will shut off that stream of content in an instant, leading to a 502 Bad Gateway Error.

Check the Logs

Nearly every web application will keep some form of server-side logs. Application logs contain the history of what the application did, such as requested pages, connected servers, database results, and so forth. Server logs are related to the actual hardware that is running the application, and will often provide details about the health and status of all connected services. 

Google «logs [PLATFORM_NAME]» if you’re using a CMS, or «logs [PROGRAMMING_LANGUAGE]» and «logs [OPERATING_SYSTEM]» if you’re running a custom application for more information on finding the logs. 

Application Code or Script Bugs

The problem may be in the custom code within your application. Try diagnosing and debugging your application by going through your application’s code and server logs. Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process. This will allow you to recreate and view the exact scenario that lead to the 502 Error.

If a 502 Bad Gateway Error is popping up within your application, consider an error management tool. Airbrake’s error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake ensures you receive round-the-clock status updates on your application’s health and error rates. Plus, no matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. 

Check out Airbrake’s error & performance monitoring software today! See for yourself why so many of the world’s best engineering teams use Airbrake by creating your free developer account here. With your free account, you’ll have access to unlimited monitoring for the first 30 days.

Note: We published this post in October 2017 and recently updated it in February 2022.

  • Ошибка resource file not found
  • Ошибка resizebuffers failed device removed device hung
  • Ошибка resident evil village d3d12
  • Ошибка resident evil 7 builder modules render os renderdevice dx11 cpp 1661 direct3d 11
  • Ошибка reshade setup was not successful