Ошибка 502 server failed

Ошибка 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  Bad Gateway 1
Что значит плохой шлюз: ошибка 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. Откройте командную строку. Для этого введите в поисковую строку «Командная строка» и выберите появившееся приложение:



502  Bad Gateway 2

  1. Введите команду:

ipconfig /flushdns

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



502  Bad Gateway 3

  1. Откройте терминал клавишами Ctrl+Alt+T.
  2. Введите команду:

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

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

sudo killall -HUP mDNSResponder

Готово, вы очистили кеш DNS. Попробуйте заново зайти на сайт.

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

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

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



502  Bad Gateway 4

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

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

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

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



502  Bad Gateway 5

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

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

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

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

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

  1. 1.

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

  2. 2.

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

  3. 3.

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



    502  Bad Gateway 6

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

Проверьте, как работают вспомогательные службы, например 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, делая работу невозможной.



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

В статье рассказывается:

  1. Общая характеристика ошибки 502 Bad Gateway
  2. Причины возникновения ошибки 502
  3. Советы пользователю по исправлению ошибки 502
  4. Рекомендации администратору по исправлению ошибки 502
  5. Пройди тест и узнай, какая сфера тебе подходит:
    айти, дизайн или маркетинг.

    Бесплатно от Geekbrains

Общая характеристика ошибки 502 Bad Gateway

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

В переводе ошибка 502 Bad Gateway означает «плохой шлюз», соответственно, проблема на шлюзе, в роли которого выступает прокси-сервер. То есть баг возникает в случае, если прокси не может получить данные от источника. Код состояния HTTP 502 веб-сервер использует для описания ошибки.

Общая характеристика ошибки 502 Bad Gateway

Общая характеристика ошибки 502 Bad Gateway

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

Также эта ошибка может иметь и другие формулировки:

  • Error 502.
  • Bad 502 Gateway.
  • 502 Error.
  • 502 Proxy Error.
  • Bad Gateway: Registered endpoint failed to handle the request, Temporary 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.
  • HTTP 502.
  • HTTP Error 502 Bad Gateway.

pdf иконка

Топ-30 самых востребованных и высокооплачиваемых профессий 2023

Поможет разобраться в актуальной ситуации на рынке труда

doc иконка

Подборка 50+ бесплатных нейросетей для упрощения работы и увеличения заработка

Только проверенные нейросети с доступом из России и свободным использованием

pdf иконка

ТОП-100 площадок для поиска работы от GeekBrains

Список проверенных ресурсов реальных вакансий с доходом от 210 000 ₽

Уже скачали 22620 pdf иконка

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

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

  • Большое количество посетителей одновременно. Возможности сервера ограничены, потому просматривать сайт может лишь определенное количество пользователей. Максимальное число зависит от мощности сервера и настроек, которые установил владелец ресурса. Если одновременно на сайт зайдет слишком большое количество пользователей, то сервер не выдержит нагрузку, и страница выдаст код ошибки 502. Например, такие ситуации часто случаются в интернет-магазинах в период акций и сезонных распродаж.
  • Хакерская атака (DDoS-атака). Хакеры, создавая большое количество запросов, имитируют огромный наплыв пользователей, вследствие чего сервер перегружается и выходит из строя.

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

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

Ошибка 500: причины и способы устранения

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

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

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

Советы пользователю по исправлению ошибки 502

Ошибка 502: что делать?

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

Скачать
файл

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

Советы пользователю по исправлению ошибки 502

Советы пользователю по исправлению ошибки 502
  • Попробуйте другой сервис. Если ошибка при открытии сайта возникает только на одном устройстве, возможно, проблема в настройках конкретной программы. Решить ее может помочь использование другого браузера.
  • Отключите расширения и плагины. Причиной ошибки могут быть плагины и расширения (особенно для работы с прокси- и VPN-сервисами), которые блокируют доступ к некоторым сайтам. Попробуйте отключить их и снова зайти на страницу.
  • Очистите кэш DNS. DNS-кэш – это своего рода база данных, которая временно хранит IP-адреса ранее посещенных сайтов с вашего компьютера, чтобы впоследствии они загружались быстрее. При смене DNS данные из памяти будут отправлять по старому пути, и в браузере появится код ошибки 502. После очистки кэша сервис будет обращаться уже к новому IP-адресу.

Ниже приведены инструкции для разных операционных систем:

  • В Windows 10, чтобы избавиться от ошибки 502, комбинацией клавиш Win+R откройте командную строку, введите «cmd» и нажмите OK. В открывшемся окне наберите команду ipconfig /flushdns и нажмите Enter. Дождитесь оповещения об успешной очистке кэша.
  • В Windows 7 в консоли введите команду ipconfig /flushdns и нажмите Enter. Затем выполните команды net stop dnscache и net start dnscache, чтобы перезапустить службу DNS-клиента.
  • В macOS нажмите на иконку поиска в правом верхнем углу и напишите «Терминал», кликните по найденному приложению. В открывшемся окне введите команду sudo killall -HUP mDNSResponder.
  • В Linux запустите терминал из основного меню или сочетанием клавиш Ctrl + Alt + T. Для Ubuntu – введите команду sudo service network-manager restart и нажмите Enter (иногда она работает и на других дистрибутивах). Для иных вариантов попробуйте sudosystem-resolve –flush-caches или sudo /etc/init.d/nscd restart.

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

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

Рекомендации администратору по исправлению ошибки 502

В первую очередь необходимо проверить журнал ошибок

В WordPress он расположен в папке wp-content, имя файла debug.log. Если такого файла нет или он пустой, то нужно включить запись логов в конфигурационном файле wp-config.php.

Дарим скидку от 60%
на курсы от GeekBrains до 24 сентября

Уже через 9 месяцев сможете устроиться на работу с доходом от 150 000 рублей

Забронировать скидку


Если у вас VPS/VDS или выделенный сервер, нужно дополнительно посмотреть логи сервера. Это поможет определить:

  • влияют ли обновления на сервере на возникновение ошибки 502;
  • признаки DDoS-атаки (массовые однотипные запросы);
  • подозрительную активность с некоторых IP-адресов;
  • отсутствие соединения между вашими серверами Nginx, Apache и т. д.

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

Использование команды top

Исправление ошибки 502 на виртуальном сервере можно начать с проверки командой top (на виртуальном хостинге такой вариант чаще всего недоступен).

Рекомендации администратору по исправлению ошибки 502

Рекомендации администратору по исправлению ошибки 502

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

  • Недостаточно памяти сервера. На это укажет аббревиатура OOM (out of memory) в результатах или же в параметре Mem – free (свободная память) будет слишком маленькое число.
  • Если ошибка 502 по причине нехватки памяти возникает все чаще, вероятно, посещаемость площадки выросла, и вам нужно увеличить на сервере объем оперативной памяти или выбрать другой тариф.
  • Недостаточно лимита php-cgi процессов для обработки запросов пользователей. Возможно, установлены слишком маленькие лимиты. Попробуйте их увеличить в конфигурационном файле httpd.conf.

Проверьте плагины в WordPress

Если ваш сайт создан на WordPress, некоторые плагины и темы могут влиять на работу сервера. Войдите в панель управления. Если вы пользуетесь услугой REG.Site, сделать это можно из личного кабинета. Перейдите во вкладку «Плагины» –«Установленные». Нажмите «Деактивировать» у того, который, по вашему мнению, повлиял на работу сайта.

Только до 25.09

Скачай подборку материалов, чтобы гарантированно найти работу в IT за 14 дней

Список документов:


ТОП-100 площадок для поиска работы от GeekBrains


20 профессий 2023 года, с доходом от 150 000 рублей


Чек-лист «Как успешно пройти собеседование»

Чтобы получить файл, укажите e-mail:

Введите e-mail, чтобы получить доступ к документам

Подтвердите, что вы не робот,
указав номер телефона:

Введите телефон, чтобы получить доступ к документам


Уже скачали 52300

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

Проверьте, как работают вспомогательные службы, например, MySQL и Memcached

Порой они могут быть причиной ошибки 502.

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

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

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

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

Ошибка 400: причины и способы устранения

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

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

Попросите помощи у коллег

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

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

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

Он проанализирует проблему, выяснит причину возникновения ошибки и устранит ее.

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

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?

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.

Error Code 502 Bad Gateway Error
Error Type Server-side error
Error Variations “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
Error Causes Server overload
Browser issues
DNS issues
Web host issues
Firewall blocks
Plugins and themes errors

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.

Check Out Our Video Guide to Fixing Different Types of 500 Errors

What Causes the 502 Bad Gateway Error?

The most likely causes of the 502 Bad Gateway are:

  1. Server overload: the server ran out of resources and crashed, triggering an HTTP error 502. The possible reasons for this could be an unexpected spike in traffic or low memory.
  2. Browser problems: your browser version is outdated or maybe there are corrupted files in your browser cache.
  3. Firewall blocks: your firewall might be detecting false threats and blocking internet providers or IP addresses.

502 Bad Gateway Error Variations

502 bad gateway error in Chrome

502 bad gateway error in Chrome

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? 13 Methods

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 ways to fix the 502 bad gateway error to 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.

2. Check the Site Status

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. There are also other tools that can help.

downforeveryoneorjustme

downforeveryoneorjustme

3. Try a Different Browser

You could try a different browser to rule that out as an issue. If you’re using Google Chrome, for example, try using Microsoft Edge.

In case the error goes away, it might be a good idea to delete and reinstall the browser you initially used.

4. Try in Incognito Mode

You can also access the site in Incognito mode. If the 502 bad gateway error doesn’t happen, the problem might be caused by a browser extension.

But how to identify the culprit extension? Try disabling them gradually, one after the other, checking if the website will open normally.

When this happens, you will have deleted the extension that was blocking your access.

5. Test on Another Device

If it looks like a problem on your end, you can try accessing the website on a different device.

Do the test: use your cell phone’s mobile data to access the page you want to see. If you succeed, restart your computer and other networking equipment, following the classic tip of unplugging your wireless router, waiting a moment, and plugging it back in.

That way you will understand if the error is related to your networking devices or something else.

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

7. Check for DNS Issues

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.

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

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

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

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

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

13. Check for PHP Timeout Issues

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 one server on the internet received an invalid response from another server. It’s a generic error alerting you that there’s something wrong with a website’s server communication.

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. Check the Site Status
  3. Try a Different Browser
  4. Try in Incognito Mode
  5. Test on Another Device
  6. Clear Your Browser Cache
  7. Check for DNS Issues
  8. Check With Your Host
  9. Temporarily Disable CDN or Firewall
  10. Check Your Plugins and Themes
  11. Check Logs
  12. Restart PHP
  13. Check for PHP Timeout Issues

Brian Jackson

Brian has a huge passion for WordPress, has been using it for over a decade, and even develops a couple of premium plugins. Brian enjoys blogging, movies, and hiking. Connect with Brian on Twitter.

  • LinkedIn

  • Twitter

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server. In the case of Nginx, a 502 bad gateway error occurs when the server cannot establish a connection with the upstream server or when the upstream server returns an invalid response.

This error is commonly seen when trying to access a website or web application that is hosted behind a reverse proxy or load balancer.

There are multiple variations of 502 Bad gateway Nginx Error you might find on different sites. For example:

  • HTTP Error 502- Bad Gateway
  • 502 Proxy Error
  • 502 Bad Gateway
  • 502 Service Temporarily Overloaded
  • HTTP 502
  • 502 Bad Gateway NGINX
  • Error 502

Nginx is a well-known open-source web server that is highly popular for its performance, scalability, and flexibility. However, similar to other web servers, Nginx can face errors that hinder its ability to deliver content to clients. One such error is the 502 Bad Gateway Nginx error.

Encountering errors can be quite frustrating and confusing, especially if you are not technically proficient. You may come across several similar prominent errors, such as the white screen of death, and the error establishing database connection. But 502 bad gateway nginx error is a very popular one.

There can be multiple possible reasons for this error to happen and therefore different ways to troubleshoot it. In this post, we will tell you what 502 bad gateway Nginx really means, its possible causes and what are the best troubleshooting method you must follow.

Let us get started!



Read: 🚩 15 Methods to Fix 502 Bad Gateway Error on Your Website


What Causes a 502 Bad Gateway Nginx Error?

There can be several reasons why a 502 Bad Gateway error may occur in Nginx, but here are some of the most common ones listed down below:

Server Overload

When a backend server receives too many requests, it can become overloaded and fail to respond within the timeout period. This causes a 502 error as the upstream server cannot fulfill the client’s request. Proper server sizing, resource allocation, load balancing, and scaling strategies can prevent server overload.

Connectivity Issues

  • Connectivity issues can cause a 502 Bad Gateway error in Nginx when there is a problem with the network connection between the reverse proxy server and the backend server.
  • This can happen due to network congestion, misconfigured network settings, or hardware failures.
  • When the reverse proxy server attempts to forward a request to the backend server but cannot establish a connection, it returns a 502 error to the client.
  • The error occurs because the reverse proxy server acts as an intermediary between the client and the backend server and is unable to connect to the backend server to fulfill the client’s request.
  • Troubleshooting network settings, checking firewall rules, and monitoring network traffic can help fix the issue.

DNS Issues

  • DNS issues can cause a 502 Bad Gateway error in Nginx when the DNS resolution for the backend server fails.
  • This can happen due to incorrect DNS configurations, DNS server failures, or DNS caching issues.
  • When a client sends a request to the reverse proxy server, the reverse proxy server needs to resolve the domain name of the backend server to an IP address.
  • If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 error being returned to the client.

Read: 🚩 What is DNS?


Firewall Restrictions

  • Firewall restrictions can cause a 502 Bad Gateway error in Nginx when a firewall blocks the connection between the reverse proxy server and the backend server.
  • This can happen when the firewall is configured to restrict traffic to and from specific IP addresses or ports.
  • When the reverse proxy server attempts to connect to the backend server, but the firewall blocks the connection, it returns a 502 error to the client.
  • This occurs because the reverse proxy server acts as an intermediary between the client and the backend server and cannot establish a connection with the backend server to fulfill the client’s request.
  • To fix firewall-related issues causing a 502 error, you may need to adjust firewall rules to allow traffic to flow between the reverse proxy and backend servers.

Software Bugs

  • A 502 Bad Gateway error may occur due to a software bug or misconfiguration in the reverse proxy server or backend server.
  • This error can happen because of coding errors or misconfigurations of server modules or applications.
  • If the software or configuration of either server contains a bug, it may fail to handle requests or respond within the timeout period, resulting in a 502 error being returned to the client.
  • To fix software-related issues causing a 502 error, you may need to examine the logs of both the reverse proxy and backend servers to identify any errors or warning messages.

PHP-FMP is Taking too long to respond

  • PHP-FPM (FastCGI Process Manager) can cause a 502 Bad Gateway error in Nginx when it fails to respond within the timeout period or encounters a critical error.
  • This error can happen due to insufficient resources, misconfiguration, or a bug in the PHP code.
  • PHP-FPM is a popular way of running PHP applications in Nginx, where Nginx sends the request to PHP-FPM and it processes the PHP code and returns the result to Nginx, which then sends the response back to the client.
  • To fix PHP-FPM-related issues, you may need to adjust the PHP-FPM configuration to increase the number of processes or threads or adjust the timeout settings.
  • You may also need to examine the PHP code to identify and fix any bugs or performance issues.
  • Additionally, monitoring the server logs and system resources can help identify any patterns or trends that could indicate a larger issue with PHP-FPM.

Read: 🚩 How to Fix HTTP 504 Gateway Timeout Error?


How to Fix a 502 Bad Gateway Nginx?

Here are some best solutions that you can follow to fix a 502 Bad Gateway Nginx error:

  • Check the status of Nginx
  • Check Backend Server Status
  • Check the DNS configuration
  • Check the Firewall Configuration
  • Increase the Buffer Size
  • Restart Nginx Server
  • Check PHP-FPM status

Check the status of Nginx

The first thing you need to do is to check whether Nginx is running and responding to requests or not. To do that, run the following command given below:

systemctl status nginx

If the Nginx is running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2022-10-11 10:25:41 UTC; 1 days ago
Docs: https://httpd.nginx.org/docs/2.4/

If the Nginx is not running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Fri 2022-10-11 10:25:41 UTC; 25s ago
Docs: https://httpd.nginx.org/docs/2.4/

Now, in case the Nginx is not running, you have to start it again by using the following command,

systemctl start nginx

Check Backend Server Status

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

curl -I http://backend-server-ip-address/

• Replace “backend-server-ip-address” with the IP address of your backend server.

• Check the HTTP status code in the output of the command. If the backend server is running correctly, you should see a status code of 200 OK.

• If you receive a status code other than 200, it indicates that there may be an issue with the backend server. You can further investigate the issue by examining the logs of the backend server to identify any errors or warning messages.

Check the DNS configuration

If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 Bad Gateway error being returned to the client. Therefore, it is important to verify that the DNS configuration for the backend server is correct.

To check the DNS configuration, you can perform the following steps:

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

nslookup backend-server-domain-name

Replace “backend-server-domain-name” with the domain name of your backend server.

• Check the output of the command to verify that the correct IP address is returned for the backend server.

  • If the output of the command indicates that the DNS resolution failed, there may be an issue with the DNS configuration. You can further investigate the issue by checking the DNS settings for the domain name of the backend server, or by contacting your DNS provider for assistance.

Check the Firewall Configuration

It is advised to check the firewall logs for an unusual block. Sometimes Firewalls also prevent or block sites. To overcome this issue, you need to temporarily disable your firewalls and check whether the issue persists or is resolved.

Increase the Buffer Size

Increasing the buffer size allows Nginx to store more data from the server’s response, ensuring that the response is complete and error-free. To increase the buffer size, you need to edit the Nginx configuration file and add the following directives.

  • proxy_buffer_size: Sets the size of each buffer. The default value is usually 4K. You can increase it to a higher value depending on your server’s requirements. For example, to set the buffer size to 16K, add the following line to your configuration file:

proxy_buffer_size 16k;

  • proxy_buffers: Sets the number of buffers to allocate. The default value is usually 8. You can increase it to a higher value depending on your server’s requirements. For example, to set the number of buffers to 32 and the buffer size to 16K, add the following line to your configuration file:

proxy_buffers 32 16k;


Note: It’s important to note that increasing the buffer size and number of buffers will increase memory usage on the server. So, you should experiment with different buffer sizes and buffer numbers to find the optimal setting for your server and application.


  • After making changes to the Nginx configuration file, save the file and restart Nginx for the changes to take effect. You can do this by running the following command:

sudo service nginx restart

Restart Nginx Server

In some cases, just restarting the Nginx server may resolve the 502 bad gateway Nginx error. To do this,

You need to run a command in your terminal or shell. The exact command depends on the operating system and distribution you are using, but here are a few examples:

  • Ubuntu and Debian:

sudo service nginx restart

  • CentOS, Fedora, and RHEL:

sudo systemctl restart nginx

  • macOS:

sudo nginx -s reload

These commands will gracefully restart the Nginx server, meaning that it will wait for any active connections to finish before shutting down and starting again.

Check PHP-FPM status

Sometimes, the 502 Bad Gateway Nginx error can also be triggered by PHP-FPM not running. Therefore, it is necessary to check the status of PHP-FPM to ensure it is running properly.

To check the running status, you can use the following command,

sudo service php-fpm status

If PHP-FPM is running, you should see a message stating that it is active.

However, in case PHP-FPM is not running, you can try restarting it using the following command:

sudo service php-fpm restart

This command will restart the PHP-FPM service, which can help resolve any issue that might be triggering a 502 bad gateway Nginx error.


Summary

A 502 Bad Gateway Nginx error is a common error that Nginx users may encounter. It is typically caused by connectivity issues, server overload, DNS issues, firewall restrictions, or software bugs.

However, following the steps outlined in this article, you can troubleshoot and resolve a 502 bad gateway nginx error.

If none of the above methods have worked for you, unfortunately, consider seeking assistance from Nginx forums or a highly experienced and qualified Nginx consultant.

If you have any tips or suggestions regarding the 502 Bad Gateway Nginx error that we may have missed in this post or if you would like to share your experience with the same, please let us know in the comment section below. We welcome your input.


Read: 🚩 How to fix HTTP 500 Internal Server Error in WordPress?


Frequently Asked Questions

How do I fix 502 Bad gateway nginx?

You can fix 502 Bad Gateway nginx error by following the below methods:
1. Check the status of Nginx
2. Check Backend Server Status
3. Check the DNS configuration
4. Check the Firewall Configuration
5. Increase the Buffer Size
6. Restart Nginx Server
7. Check PHP-FPM stat

How do I check my nginx status?

To check the nginx status, Run the following command given below:
systemctl status nginx
The Output will show whether the nginx is running or not.

What is a 502 Bad gateway error?

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server.

439

439 people found this article helpful

This error is usually caused by two different internet servers that are having trouble communicating

Updated on December 15, 2022

The 502 Bad Gateway error is an HTTP status code that means that one server on the internet received an invalid response from another server. These errors are completely independent of your particular setup, meaning that you could see one in any browser, on any operating system, and on any device.

The 502 Bad Gateway error displays inside the internet browser window, just like web pages do.

What Does a 502 Bad Gateway Error Look Like?

Each website can customize the 502 Bad Gateway. While it’s fairly uncommon, different web servers do describe this error differently.

Below are some common ways you might see it:

  • 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

A Bad Gateway error received in Windows Update generates a 0x80244021 error code or the message WU_E_PT_HTTP_STATUS_BAD_GATEWAY.

When Google services, like Google Search or Gmail, are experiencing a 502 Bad Gateway, they often show Server Error, or sometimes just 502, on the screen.

What Causes a 502 Bad Gateway Error?

Bad Gateway errors are often caused by issues between online servers that you have no control over. However, sometimes, there is no real issue but your browser thinks there’s one thanks to a problem with your browser, an issue with your home networking equipment, or some other in-your-control reason.

Microsoft IIS web servers often give more information about the cause of a particular 502 Bad Gateway error by adding an extra digit after the 502, as in HTTP Error 502.3 — Web server received an invalid response while acting as a gateway or proxy, which means Bad Gateway: Forwarder Connection Error (ARR).

An HTTP Error 502.1 — Bad Gateway error refers to a CGI application timeout problem and is better to troubleshoot as a 504 Gateway Timeout issue.

How to Fix a 502 Bad Gateway Error

The 502 Bad Gateway error is often a network error between servers on the internet, meaning the problem wouldn’t be with your computer or internet connection.

However, since it is possible that there’s something wrong on your end, here are some fixes to try:

  1. Try loading the URL again by pressing F5 or Ctrl+R (Command+R on a Mac) on your keyboard, or by selecting the refresh/reload button.

    While the 502 Bad Gateway error is usually indicating a networking error outside of your control, it could be extremely temporary. Trying the page again will often be successful.

  2. Start a new browser session by closing all open browser windows and then opening a new one. Then try opening the web page again.

    It’s possible that the 502 error you received was due to an issue on your computer that occurred sometime during this use of your browser. A simple restart of the browser program itself could solve the problem.

  3. Clear your browser’s cache. Outdated or corrupted files that are being stored by your browser could be causing 502 Bad Gateway issues.

    Clearing the Cache in Edge.

    Removing those cached files and trying the page again will solve the problem if this is the cause.

  4. Delete your browser’s cookies. For similar reasons as mentioned above with cached files, clearing stored cookies could fix a 502 error.

    If you’d rather not clear all of your cookies, you could first try removing only those cookies related to the site you’re getting the 502 error on. It’s best to remove them all but it won’t hurt to try the clearly applicable one(s) first.

  5. Start your browser in Safe Mode: We have instructions for Firefox, Chrome, or Edge. Running a browser in Safe Mode means to run it with default settings and without add-ons or extensions, including toolbars.

    Internet Explorer in Safe Mode.

    If the 502 error no longer appears when running your browser in Safe Mode, you know that some browser extension or setting is the cause of the problem. Return your browser settings to default and/or selectively disable browser extensions to find the root cause and permanently fix the problem.

    A browser’s Safe Mode is similar in idea to the Safe Mode in Windows but it’s not the same thing. You do not need to start Windows in Safe Mode to run any browser in its particular «Safe Mode.»

  6. Try another browser. Popular browsers include Firefox, Chrome, Edge, Opera, and Safari.

    If an alternative browser doesn’t produce a 502 Bad Gateway error, you now know that your original browser is the source of the problem. Assuming you’ve followed the above troubleshooting advice, now would be the time to reinstall your browser and see if that corrects the problem.

  7. Restart your computer. Some temporary issues with your computer and how it’s connecting to your network could be causing 502 errors, especially if you’re seeing the error on more than one website. In these cases, a restart would help.

  8. Restart your networking equipment. Issues with your modem, router, switches, or other networking devices could be causing 502 Bad Gateway or other 502 errors. A simple restart of these devices could help.

    The order you turn off these devices isn’t particularly important, but be sure to turn them back on from the outside in. Check out that link above for more detailed help on restarting your equipment if you need it.

  9. Change your DNS servers, either on your router or on your computer or device. Some Bad Gateway errors are caused by temporary issues with DNS servers.

    Unless you’ve previously changed them, the DNS servers you have configured right now are probably the ones automatically assigned by your ISP. Fortunately, a number of other DNS servers are available for your use that you can choose from.

  10. Contacting the website directly might also be a good idea. Chances are, assuming they’re at fault, the website administrators are already working on correcting the cause of the 502 Bad Gateway error, but feel free to let them know about it.

    Most websites have social networking accounts they use to help support their services. Some even have telephone and email contacts.

    If you suspect a website is down for everyone, especially a popular one, checking X (formerly Twitter for chatter about the outage is often very helpful. The best way to do this is to search for #websitedown on X, as in #cnndown or #instagramdown. There are other ways to see if a website is down if social media isn’t helpful.

  11. Contact your internet service provider. If your browser, computer, and network are all working and the website reports that the page or site is working for them, the 502 Bad Gateway issue could be caused by a network issue that your ISP is responsible for.

  12. Come back later. At this point in your troubleshooting, the 502 Bad Gateway error message is almost certainly an issue with either your ISP or with the website’s network—one of the two parties might have even confirmed that for you if you contacted them directly. Either way, you’re not the only one seeing the 502 error and so you’ll need to wait until the problem is solved for you.

FAQ

  • How do I fix a 404 error?

    To fix a 404 Page Not Found error, try reloading the web page and ensure you typed the correct URL. You may have the wrong URL, so try searching for the site from a search engine. You can also try clearing your browser’s cache and changing the DNS servers, but if it’s the website’s problem, there’s nothing you can do.

  • How do I fix a 500 internal server error?

    There isn’t much you can do to fix a 500 internal server error; the problem usually appears when there’s an issue with the page or site’s programming. However, you can try reloading the page, clearing your browser’s cache, deleting browser cookies, or returning to the website later.

  • How do I fix a 403 Forbidden error on Google Chrome?

    There isn’t much you can do to fix a 403 Forbidden error because it typically stems from the site’s development and design. To see if the problem is on your end, try checking for URL errors and clearing your browser’s cache and cookies. See if the site is working for others; if so, contact the webmaster.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 5006 0x80070005 при работе программы установки
  • Ошибка 502 ru center
  • Ошибка 501 при отправке почты
  • Ошибка 501 на газовом котле алексия
  • Ошибка 5014 bmw

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии