При формировании запроса произошла ошибка proxy error 502

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

Ошибка 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. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.
Icon Ex Номер ошибки: Ошибка 502 Proxy Error
Название ошибки: Internet Explorer Error Code 502 Proxy Error
Описание ошибки: Ошибка 502 Proxy Error: Возникла ошибка в приложении Internet Explorer. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Internet Explorer
Относится к: Windows XP, Vista, 7, 8, 10, 11

Обзор «Internet Explorer Error Code 502 Proxy Error»

«Internet Explorer Error Code 502 Proxy Error» часто называется ошибкой во время выполнения (ошибка). Разработчики программного обеспечения, такие как SoftwareDeveloper, обычно работают через несколько этапов отладки, чтобы предотвратить и исправить ошибки, обнаруженные в конечном продукте до выпуска программного обеспечения для общественности. К сожалению, иногда ошибки, такие как ошибка 502 Proxy Error, могут быть пропущены во время этого процесса.

Ошибка 502 Proxy Error может столкнуться с пользователями Internet Explorer, если они регулярно используют программу, также рассматривается как «Internet Explorer Error Code 502 Proxy Error». Когда это происходит, конечные пользователи могут сообщить Microsoft Corporation о наличии ошибок «Internet Explorer Error Code 502 Proxy Error». Затем Microsoft Corporation исправит ошибки и подготовит файл обновления для загрузки. В результате разработчик может использовать пакеты обновлений для Internet Explorer, доступные с их веб-сайта (или автоматическую загрузку), чтобы устранить эти ошибки 502 Proxy Error проблемы и другие ошибки.

Что генерирует ошибку времени выполнения 502 Proxy Error?

Ошибки выполнения при запуске Internet Explorer — это когда вы, скорее всего, столкнетесь с «Internet Explorer Error Code 502 Proxy Error». Вот три наиболее заметные причины ошибки ошибки 502 Proxy Error во время выполнения происходят:

Ошибка 502 Proxy Error Crash — программа обнаружила ошибку 502 Proxy Error из-за указанной задачи и завершила работу программы. Это возникает, когда Internet Explorer не работает должным образом или не знает, какой вывод будет подходящим.

Утечка памяти «Internet Explorer Error Code 502 Proxy Error» — ошибка 502 Proxy Error приводит к постоянной утечке памяти Internet Explorer. Потребление памяти напрямую пропорционально загрузке ЦП. Возможные причины из-за отказа Microsoft Corporation девыделения памяти в программе или когда плохой код выполняет «бесконечный цикл».

Error 502 Proxy Error Logic Error — Ошибка программной логики возникает, когда, несмотря на точный ввод от пользователя, производится неверный вывод. Это может произойти, когда исходный код Microsoft Corporation имеет уязвимость в отношении передачи данных.

Основные причины Microsoft Corporation ошибок, связанных с файлом Internet Explorer Error Code 502 Proxy Error, включают отсутствие или повреждение файла, или, в некоторых случаях, заражение связанного Internet Explorer вредоносным ПО в прошлом или настоящем. Для устранения неполадок, связанных с файлом Microsoft Corporation, большинство профессионалов ПК заменят файл на соответствующую версию. В качестве дополнительного шага по устранению неполадок мы настоятельно рекомендуем очистить все пути к неверным файлам и ссылки на расширения файлов Microsoft Corporation, которые могут способствовать возникновению такого рода ошибок, связанных с Internet Explorer Error Code 502 Proxy Error.

Ошибки Internet Explorer Error Code 502 Proxy Error

Internet Explorer Error Code 502 Proxy Error Проблемы, связанные с Internet Explorer:

  • «Ошибка программного обеспечения Internet Explorer Error Code 502 Proxy Error. «
  • «Недопустимая программа Win32: Internet Explorer Error Code 502 Proxy Error»
  • «Извините, Internet Explorer Error Code 502 Proxy Error столкнулся с проблемой. «
  • «К сожалению, мы не можем найти Internet Explorer Error Code 502 Proxy Error. «
  • «Отсутствует файл Internet Explorer Error Code 502 Proxy Error.»
  • «Ошибка запуска программы: Internet Explorer Error Code 502 Proxy Error.»
  • «Internet Explorer Error Code 502 Proxy Error не работает. «
  • «Internet Explorer Error Code 502 Proxy Error остановлен. «
  • «Ошибка в пути к программному обеспечению: Internet Explorer Error Code 502 Proxy Error. «

Обычно ошибки Internet Explorer Error Code 502 Proxy Error с Internet Explorer возникают во время запуска или завершения работы, в то время как программы, связанные с Internet Explorer Error Code 502 Proxy Error, выполняются, или редко во время последовательности обновления ОС. Отслеживание того, когда и где возникает ошибка Internet Explorer Error Code 502 Proxy Error, является важной информацией при устранении проблемы.

Создатели Internet Explorer Error Code 502 Proxy Error Трудности

Эти проблемы Internet Explorer Error Code 502 Proxy Error создаются отсутствующими или поврежденными файлами Internet Explorer Error Code 502 Proxy Error, недопустимыми записями реестра Internet Explorer или вредоносным программным обеспечением.

Точнее, ошибки Internet Explorer Error Code 502 Proxy Error, созданные из:

  • Поврежденные ключи реестра Windows, связанные с Internet Explorer Error Code 502 Proxy Error / Internet Explorer.
  • Вредоносные программы заразили Internet Explorer Error Code 502 Proxy Error, создавая повреждение.
  • Другая программа злонамеренно или по ошибке удалила файлы, связанные с Internet Explorer Error Code 502 Proxy Error.
  • Другая программа находится в конфликте с Internet Explorer и его общими файлами ссылок.
  • Поврежденная загрузка или неполная установка программного обеспечения Internet Explorer.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

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

Что такое ошибка 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 и другие ошибки веб-страниц

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.

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.

Что такое ошибка 502 Bad Gateway и как исправить?

Здравствуйте, друзья!

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

Одной из самых известных и популярных среди всех является ошибка «502 Bad Gateway».

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

Тем не менее, проверка своего соединения всегда стоит того.

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

Что такое ошибка «502 Bad Gateway»?

Для облегчения понимания отображается ошибка «502 Bad Gateway Error», когда веб-сервер не может получить действительный ответ от входящего сервера.

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

После обработки запроса веб-сервер отправляет обратно запрошенные ресурсы.

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

Есть множество причин, по которым вы можете получить такой ответ.

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

Иногда даже неправильная конфигурация брандмауэра может вызвать ошибку «502 Bad Gateway».

Вариация ошибки «502 Bad Gateway»

С множеством веб-браузеров, веб-сервисов и операционных систем вы действительно можете найти различные варианты «502 Bad Gateway».

В этом разделе мы собрали все варианты ошибки «502 Bad Gateway Error», с которыми вы можете столкнуться.

  • 502 Bad Gateway;
  • HTTP Error 502: Bad Gateway;
  • Error 502;
  • 502 Proxy Error;
  • 502 Service Temporarily Overloaded;
  • 502 Server Error: The server encountered a temporary error and could not complete your request;
  • 502 bad gateway Cloudflare;
  • Temporary Error (502);
  • HTTP 502”.

7 способов исправить ошибку «502 Bad Gateway»

Независимо от того, как ошибка представлена вам, с вашей машиной все в порядке.

В большинстве случаев это что-то со стороны сервера.

При этом есть еще некоторые исправления, которые вы можете попробовать со своей стороны.

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

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

Это само собой разумеется, но обновление вашей веб-страницы может мгновенно решить вашу проблему.

Фактически, в большинстве случаев ошибка «502 Bad Gateway Error» носит временный характер.

Вы можете просто перезагрузить страницу с помощью обновить страницу в браузере или нажатием клавиш F5, Ctrl + F5 или CMD + R.

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

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

2. Проверка, доступен ли этот веб-сайт для всех

Статус в сети

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

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

Наиболее часто используемые — это downforeveryoneorjustme.com и isitdownrightnow.com.

Оба сайта работают одинаково.

Все, что вам нужно сделать, это вставить URL-адрес, который вы предпочитаете проверить, и вы получите соответствующие результаты.

В случае, если вы получите сообщение о том, что веб-сайт недоступен для всех, вы вряд ли сможете что-либо сделать со своей стороны.

Напротив, если отчет показывает, что веб-сайт работает, вам необходимо проверить соединение на своем конце.

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

3. Выберите другой браузер

веб-браузеры

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

Самое простое решение — просто проверить веб-сайт в другом веб-браузере.

Вы можете использовать Microsoft Edge, Mozilla Firefox, Google Chrome или Apple Safari.

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

4. Очистка кэша и файлов cookie веб-сайта

Очистить кэш

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

Фактически, любой устаревший кэш или поврежденный файл может быть причиной ошибки «502 Bad Gateway Error».

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

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

5. Проверка подключаемых модулей и расширений браузера

Расширения

Иногда плагины и расширения браузера могут вызывать множество проблем при попытке открыть определенные веб-страницы.

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

В случае, если ошибка «502 Bad Gateway Error» устранена, вероятно, это был один из плагинов, вызывающий эту ошибку.

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

6. Перезагрузка устройства

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

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

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

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

7. Изменение DNS-сервера

Скорее всего, проблема с DNS также может вызвать ошибку «502 Bad Gateway Error».

Хотя вы не можете полностью рассматривать то же самое как исправление, всегда стоит попробовать.

Тем не менее, это также совершенно легко изменить.

В большинстве случаев DNS-сервер настраивается вашим интернет-провайдером.

Замена его на любой сторонний DNS-сервер, включая Google DNS или OpenDNS, может оказаться полезным.

Подведение итогов: ошибка «502 Bad Gateway»

Итак, это был наш список различных способов, с помощью которых вы можете фактически устранить и исправить ошибку «502 Bad Gateway Error».

Обычно это все, что вы можете сделать со своей стороны.

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

Спасибо что дочитали!

До скорых встреч! Заходите!

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

502 bad gateway — что это за ошибка? Ошибка 502 Bad Gateway может проявляться по-разному. К примеру, 502 – Service Temporarily Overloaded или HTTP Error 502 Bad Gateway.

Ошибка 502 bad gateway — что это значит?

Ошибка 502 bad gateway - что это значит?

Ошибка 502 bad gateway говорит о том, что обратный прокси-сервер (допустим, Apache) для сервера источника (например, nginx) получает некорректный ответ от исходного веб-сервера.

Посмотрев внимательнее, мы обнаружили, что Apache работает в нем как прокси nginx. Веб-сервер перезагружал http-сервис почти каждый час. Наш опыт в устранении подобных ошибок показывает, что ошибка 502 Bad Gateway появляется по одной из следующих причин:

  1. Перегруженность сервера. Веб-сервер может падать из-за нехватки ресурсов (например, оперативной памяти), вызываемой избытком выполняемых процессов или агрессивными действиями пользователей;
  2. Частая перезагрузка веб-сервера. Такое случается при ошибках конфигурации, сбоях в модулях, любых атаках, избытке выполняемых процессов и приложений. В результате пользователь видит временную 502 ошибку;
  3. Плохой код сайта. Сайты с устаревшими приложениями или корявым кодом влияют на правильное функционирование сервера и ведут к периодическому возникновению 502 ошибки;
  4. Ошибки сети. Прочие ошибки конфигурации сети (проблемы с DNS, маршрутизация, блокировка файерволом, используемым на сервере, проблемы у провайдера) также становятся причиной появления 502 ошибки сервера;
  5. Время ожидания серверного программного обеспечения. 502 ошибка неизбежна при снижении скорости выполнения запросов в nginx, когда средство кэширования (например, Varnish Cache) уходит в таймаут. Сюда же относятся и медленные запросы.

Как исправить ошибку 502 bad gateway на веб-сервере nginx

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

Затем мы покопались в конфигурации сервера, и увидели, что там отсутствовал модуль mod_rpaf. Именно это и вызывало падение сервера:

root@server [~]# ls -l /usr/local/apache/modules/mod_rpaf-2.0.so
/bin/ls: cannot access /usr/local/apache/modules/mod_rpaf-2.0.so: No such file or directory

Rpaf – это модуль Reverse proxy add forward, разработанный для серверов Apache. Он нужен в том случае, если вы задаете Nginx фронденд-сервером и хотите получить реальный IP серверных запросов.

Данный модуль не работал под Apache-2.4, поэтому мы немного его подправили. После перекомпиляции и перезагрузки Apache ошибки сегментации прекратились.

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

Вот несколько советов, как исправить ошибку 502 bad gateway:

  • Следите за тем, чтобы файлы сайта (плагины и темы) своевременно обновлялись и не устаревали;
  • Оптимизируйте и исправляйте медленные MySQL-запросы;
  • Проводите аудит серверного программного обеспечения и вовремя обновляйте модули;
  • Избегайте проблем с маршрутизацией и отслеживайте любые перегрузки/атаки на сервер.

While surfing the Internet, if an end-user encounters a 502 proxy error, he or she will not be able to view the desired web page. The error message is commonly encountered when accessing websites through a proxy server. The problem is typically caused for one of two reasons: 1 – The Internet Security and Acceleration (ISA) is configured to throw a proxy error to help guard against external or internally-based Internet threats, and 2- The client or server computers are misconfigured or using outdated software.

What is a 502 Proxy Error?

A 502 proxy error is typically thrown in the HTTP cycle. When the error occurs, a server (does not have to be a Web server) is filling a role similar to a proxy or a gateway server. When a client computer sends an HTTP request (typically a web browser, but can be any software application that is capable of making an HTTP request), it will pass through the server in order to obtain access to the desired URL. The proxy or gateway subsequently receives a 502 error, or invalid response, from the server located “upstream” in the attempt to fulfill the client request. The majority of the time the error is thrown, the upstream server is functioning appropriately. The proxy or gateway and upstream servers just cannot agree on the appropriate protocol for exchanging the information requested in the original client HTTP request. In many of these cases, either the proxy or upstream server are not configured correctly or are running incompatible software.

Why Does a 502 Proxy Error Get Thrown?

During a typical web browsing session, the following is an example of the classic HTTP cycle when a client computer and web server are communicating:502 Proxy Error

Client Computer: The IP address of the desired website will be obtained from the URL of the site from the DNS server.

Client Computer: The computer obtains an IP socket connection to the desired IP address and then sends an HTTP data stream through the IP address.

Web Server: HTTP data is sent back to the client computer in response to the original HTTP request. The HTTP response will include status codes and other useful information for the client computer.

Client Computer: If there is an error in the client’s request or server’s ability to respond, there will be an HTTP error code of 502 included in the server’s response (502 Proxy Error).

How to Fix 502 Proxy Errors (Client Side)

One of the most frustrating things for the average computer user is determining where the problem resides when receiving the 502 Proxy Error. Before engaging the webmaster of the site or one’s Internet Service Provider (ISP), it is prudent to troubleshoot the client computer to make sure that it is not the reason that the error is being thrown.

Step 1 – Close the Internet browser that you are using. If you have an alternate browser on your computer, launch that application and attempt to access the site that is throwing the 502 error. If you do not have an alternative web browser installed on your computer, restart the one you were using. A number of times, web browsers can end up having scripting errors on previous web sites impact being able to view new web pages. Some of the popular alternative web browsers to Internet Explorer include Mozilla Firefox and Google Chrome.

Step 2 – Clear the web browser’s cache to ensure that the error is not being thrown due to a legacy issue with the problem webpage or other website that you have visited recently.

Step 3 – Restart the computer if restarting the Internet browser did not work. Although more commonly encountered on computers running the Windows operating system, restarting the computer can help fix errors the computer is encountered with the local network or ISP. Once the computer has completed the restart process, launch an Internet browser and attempt to load the problem web page.

Step 4 – If still unsuccessful with clearing the 502 Proxy Error, restart the DSL or cable modem that supplies the Internet connection for your home or place of business. This may take a few minutes while the modem conducts the restart process, so do not attempt to access the problem webpage until the modem is back online.

Step 5 – Try to surf to additional websites. If the 502 error is being shown across a number (or all) of the websites that you desire to view, then the issue may reside with the ISP or local network. If this is the case, contact the ISP via phone or chat via smart phone and ask if there is an outage in the local area or specifically with the residence’s Internet service. Once corrected, attempt to access the problem websites.

Step 6 – If there is not service outage to the residence, contact the customer service department of the ISP or the admin on a local network to request a service repair person to verify the modem and wireless router (if installed) in your residence.

How to Clear Cache (Internet Explorer 9/10)

Internet Explorer 9 and Internet Explorer 10 are the two most recent releases of the popular web browser produced by the Microsoft Corporation in 2011 and 2012 respectfully. The following are the steps to take in order to clear cache, browsing history, and cookies in the browsers:

Step 1 – Open the Internet Explorer application.

Step 2 – Choose the “Tools,” “Safety,” and “Delete Browsing history” men options.

Step 3 – Ensure you uncheck the “Preserve Favorites website data” check box.

Step 4 – Check the “Temporary Internet Files” and “Cookies” check boxes followed by clicking the “Delete” menu button.

Step 5 – Acknowledge the confirmation window that appears at the bottom of the web browser to complete clearing the browser’s cache and cookies.

Step 6 – If the 502 proxy error is still thrown by the browser, it may be necessary to use advanced options to more fully clear the cache. If this is the case, exit from Internet Options if the window is still open on the browser.

Step 7 – Select the “Tools” and “Developer Tools” menu choices.

Step 8 – Choose the “Cache” menu option and then pick the “Clear Browser Cache” menu choice.

Step 9 – Select the “Yes” menu button to finish clearing the browser cache.

How to Clear Cache (Internet Explorer 7)

Internet Explorer 7 was first released by the Microsoft Corporation in October 2006. It was the first major upgrade to the browser in more than five years by Microsoft and was shipped as the default browser for Windows Vista and Windows Server 2008.

Step 1 – Open Internet Explorer 7 by double clicking the program icon on your computer’s desktop.

Step 2 – Select the “Tools” and “Internet Options” menu options.

Step 3 – Select the “General” menu tab.

Step 4 – Choose the “Delete” menu button followed by clicking the “Delete Files” menu choice.

Step 5 – Select the “Yes” button followed by choosing the “Delete Cookies” menu choice.

Step 6 – Click the “Yes” menu button and the cache will be cleared from IE7.

How to Clear Browser Cache (Mozilla Firefox)

Mozilla Firefox is an open sourced, free Internet Browser that is designed to work on the OS X, Linux, Android, and Windows operating systems. The browser implements both current and emerging web standards and has more than 20% of the world-wide market share of web browsers. Similar to Internet Explorer users, those who use the browser may have the need arise to clear the Firefox cache in order to help troubleshoot the 502 proxy error issue.

Step 1 – Open the Mozilla Firefox web browser.

Step 2 – At the top of the browser window, select or click on the Firefox button.
Step 3 – Choose the “Firefox” button and then select the “Options” menu choice.
Step 4 – Pick the “Advanced” panel and then click the “Network” menu tab.

Step 5 – Choose the “Clear Now” menu button under the “Cached Web Content” section of the menu.

Step 6 – Click the “Ok” menu button to close the “Options” window of Firefox.
Step 7 – You can also setup Firefox to automatically clear cache when it closes. Before exiting from the “Options” window, select the “Privacy” panel. Then, under the “History” Sections select the “custom settings” menu choice and select the check box located next to the “Clear history when Firefox closes” menu option. Click “Ok” to close the window  and Firefox will now be setup to clear cache when exiting the browser.

How to Clear Browser Cache (Google Chrome)

Google Chrome is released as a freeware browser by Google and was first seen on the market in early September of 2008. Since that time, it has gained a market share of 39% of all world-wide browser use. There is some debate behind these claims; however, with many still placing Chrome third in use behind Internet Explorer and Mozilla Firefox. Similar to the other major browsers, Chrome includes the ability for the end user to clear cache and other web browsing information from the program.

Step 1 – Double click the Chrome program icon located on your computer’s desktop to launch the application.
Step 2 – Select the “Chrome” menu button located on the web browser’s toolbar.

Step 3 – Select the “Tools” menu button.

Step 4 – Click the “Clear browsing data” menu option.

Step 5 – Exit from the Google Chrome Tools menu and the cache will now be cleared.

How to Clear Browser Cache (Android OS)

The Android OS is based on Linux and is primarily designed to support touchscreen mobile devices. The OS was released in 2007 and the first phone designed to run on the OS was released in 2008. The source code for the OS was released as open source under the Apache license by Microsoft, and supports the ability for end users to clear the browser cache to help troubleshoot the 502 proxy error.

Step 1 – Open or launch a browser window on the Android device by tapping the applications menu and selecting the appropriate program icon.

Step 2 – Select the menu key on the phone. It is normally located in the lower, left-hand corner of the keypad on the phone.

Step 3 – Select the “More” menu option from the listing the is subsequently displayed on the phone.

Step 4 – Select the “Settings” menu option to display the web browser settings options in the Android OS.

Step 5 – Select the “Privacy Settings” menu choice.

Step 6 – Select the “Clear Cache” and if desired, “Clear History” menu options.

Step 7 – Select the “Ok” menu button to complete clearing the cache on the Android device.

Step 8 – Attempt to visit the website that has been throwing the 502 proxy error to see if clearing the browser cache has fixed the problem.

How to Fix the 502 Proxy Error (Server Side)

If you are running IIS Server, a 502 proxy error can be generated through misconfiguration or failing to update the server. Some known cases which can result in the error being thrown include: Enabling the HTTPS inspection feature in the Microsoft Forefront Threat Management Gateway (TMG), trying to use a HTTPS URL to access a website which much have a client certificate through the Forefront TMG, and adding the site to the IIS Destination Exception list for HTTPS inspection. When this occurs, the error thrown will be similar to, “502 Proxy Error, An unknown error occurred while processing the certificate.” This specific instance of the 502 error comes from the Forefront TMG 2010 sending an empty client certificate to the web server while conducting the initial SSL handshake. IIS can throw this error when acting as either w web or gateway server.

Step 1 – Upgrade IIS to the latest version of the software available from Microsoft if the 502 error being thrown is persistent.

Step 2 – Install the Forefront Threat Management Gateway 2010 Service Pack 1 (or applicable update) if not installed during the IIS upgrade.

Step 3 – Open the “HTTPS Outbound Inspection” dialog box.

Step 4 – Choose the “No Validation option” for the web server.

Step 5 – Open Windows Notepad, and copy the script provided by Microsoft into the program.

Step 6 – Save the file to the computer with the file name, EnableHotfix982550.vbs.

Step 7 – Double click the new VBS file to complete fixing the IIS server.

Понравилась статья? Поделить с друзьями:
  • Приводя примеры истинной любви многие учащиеся обращались к гранатовому браслету где ошибка
  • При формировании запроса произошла ошибка internal server error 500 федеральное казначейство
  • Привод работает выключить зажигание porsche cayenne ошибка
  • Привод полная мощность недоступна ошибка бмв
  • Привод ошибка бмв g30