Http 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. Если для воспроизведения проблемы необходимо авторизоваться в административной части сайта, предоставьте логин и пароль для доступа.

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

Что такое ошибка 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 (ERROR 502 Bad Gateway) — это сбой, который свидетельствует о получении некорректного ответа от вышестоящего по иерархии сервера. Простыми словами это получение неправильного ответа, приводящего к невозможности загрузить контент страницы.

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

Чаще всего возникает по вине хостинга, DNS или прокси-сервера. Логика появления ошибки следующая: файлы публичного веб-сайта всегда располагаются на сервере. Пользовательский клиент (чаще всего, браузер) делает соответствующий запрос, чтобы получить данные из физического сервера и вывести их на пользовательском компьютере. Когда отправить файлы не получается — выводится ошибка с кодом от 500-й до 511-й.

Сам текст ошибки 502 может различаться. Часто встречаются варианты 502 Server Error, Bad Gateway, Temporary Error, HTTP 502 и другие. 

Как исправить ошибку 502 вебмастеру: пошаговый алгоритм

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

Недостаток вычислительных ресурсов. Тарифный план хостинга

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

Что делать?

  1. Проверьте статическую нагрузку, текущий размер оперативной памяти и размер хранилища для файлов сайта на используемом хостинге. 
  2. Управление услугами на хостинге Beget. Для базового хостинга можно менять разрешенную нагрузку, дисковую квоту и количество сайтов

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

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

  3. Проверьте оперативную память сервера. Чтобы проверить текущий объем оперативной памяти, запустите командую строку сервера, затем укажите команды free -m (либо команду tor).

Проверяем доступный объем памяти сервера. MiB Mem — постоянная память. Mib Swap — память файла подкачки

Проверяем доступный объем памяти сервера. MiB Mem — постоянная память. Mib Swap — память файла подкачки

Обратите внимание на параметры total (общий объем памяти), free (свободный объем памяти в данный момент), used (использующийся объем памяти в данный момент).

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

Увеличение лимитов FastCGI

HTTP-сервер Apache настраивается путем размещения директив в текстовых файлах конфигурации. Основной файл конфигурации обычно называется httpd.conf. Его расположение устанавливается во время компиляции, но может быть переопределено флагом командной строки -f.

Проект HTTP-сервера Apache, широко известный как Apache HTTPD или Apache, представляет собой HTTP-сервер с открытым исходным кодом, на котором работает большая часть веб-приложений. Apache HTTPD является кроссплатформенным и может работать в системах на базе Unix и Windows.

Что делать?

  1. Найдите и отредактируйте файл httpd.conf. 
  2. Измените установленное значение для FastCGI. 
  3. Увеличьте его на 500-600 пунктов.

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

Пример содержимого файла httpd.conf

Пример содержимого файла httpd.conf

Глобальные изменения на сайте: обновления, установка плагинов, изменение дизайна или структуры URL

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

Что делать?

  1. Найдите файл с логами. Обычно кнопка с доступом к логам сервера есть в административной панели. Самое частое название такого файла — access.log. Если вы не нашли его — напишите в саппорт хостинга. Уточните, что серверные логи нужны вам для решения ошибки.
  2. Проанализируйте файл с ошибками. Логи сервера с ошибками обычно по умолчанию отправляются в файл error.log
  3. Ищите значение OOM или другие ошибки. Обязательно обращайте внимание на директиву %s со значением 502 (это и есть код состояния искомой нами ошибки).

Директивы в формате combined выглядят так:

  • %s — код состояния HTTP.
  • %h — IP-адрес запроса.
  • %{User-Agent} — HTTP-заголовок.
  • %l — полное название хоста.
  • %b — отданные байты.
  • %u — пользователь.
  • %r — тип и содержимое запроса.
  • %t — время запроса.

Cloudflare

Если вы настроили Cloudflare или похожее решение против хакерских атак, попробуйте отключить эту защиту. Часто Bad Gateway ошибка возникает по вине таких сервисов. То же самое можно сказать и о сторонних сетях доставки содержимого (СDN), с которыми соединен ваш сайт.

Капча, которая используется сетью Cloudflare для защиты сайта от хакерских атак

Капча, которая используется сетью Cloudflare для защиты сайта от хакерских атак

Что делать?

  1. Временно отключите Cloudflare.
  2. Временно отключите CDN (сеть доставки содержимого).
  3. Проверьте, стала ли доступна проблемная страница. Если да — настройте используемые внешние сервисы так, чтобы они не ограничивали доступ к странице.

Важно: отключение вашего сайта от любых сервисов, которые перенаправляет ваш трафик на собственные сервера (например, тот же CloudFlare) произойдет не сразу, а только через 5-6 часов или даже дольше, так как должно произойти обновление записей DNS.

Конфликт плагинов, проблемы после обновления CMS

Всегда запоминайте (а лучше — записывайте) все изменения, которые вы делаете на сайте. Будь то установка плагина, добавление нового функционала или изменение дизайна страницы. Так вы сможете просто диагностировать источник появления ошибки 502 и сразу перейти к его устранению. Например — удалить конфликтующий плагин через админку используемой CMS.

Откат к исправно работающей версии сайта может стать решением Bad Gateway в ряде случаев.

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

Что делать?

Показываем на на примере хостинга Beget:

  1. Чтобы откатиться к исправно работающей версии сайта, откройте раздел Backup в панели управления используемого хостинга. 
  2. Раздел BackUp на хостинге Beget доступен с главной страницы

    Раздел BackUp на хостинге Beget доступен с главной страницы

    Вы можете настроить автоматическое копирование или бэкап по требованию. 

  3. Чтобы выгрузить файлы (создать бэкап), выберите необходимые файлы, отметив чекбокс слева от них:
  4. Выгружаем резервную копию выбранных данных на хостинге Beget

    Выгружаем резервную копию выбранных данных на хостинге Beget
  5. Чтобы восстановить сайт из резервной копии, выберите копию (в Beget «Текущее состояние») и затем кликните по синей стрелке: 
  6. Восстанавливаем файлы сайта из резервной копии

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

Как исправить ошибку 502 пользователю: пошаговый алгоритм

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

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

Чтобы устранить ошибку, выполните следующие действия:

  • Напишите администратору сайта о возникшей проблеме.
  • Попробуйте зайти на сайт в то время, когда поток пользователей небольшой (например, очень рано утром или ночью).
  • Отключите все плагины / расширения в используемом браузере (в редких случаях они могут приводить к конфликтам). Подтвердить этот источник сбоя поможет просмотр проблемного сайта в режиме инкогнито.
  • Очистите DNS-кэш в своей системе. Для этого нужно открыть встроенный в Windows инструмент cmd и прописать команду ipconfig /flushdns:

Запустите командную строку и укажите команду ipconfig /flushdns

Запустите командную строку и укажите команду ipconfig /flushdns

Все, DNS cache успешно очищен:

Мы успешно очистили DNS

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

Резюме: самые частые причины появления ошибки

Итак, можно вывести четыре самых распространенных сценария появления Bad Gateway на сайте:

  1. Недостаток вычислительных ресурсов. Может проявляться на очень слабых, старых машинах.
  2. Глобальные изменения на сайте: обновления, установка плагинов, изменение дизайна или структуры ссылок.
  3. Конфликт плагинов. Проблемы после обновления версии CMS.
  4. Cloudflare и подобные сервисы + CDN (сеть доставки содержимого).

Найдите свою причину и устраните ее, следуя нашему алгоритму. 

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

What does 502 Bad Gateway mean?

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

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

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

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

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

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

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

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

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

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

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

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

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

What is a 502 Bad Gateway error?

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

The different forms of 502 errors

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

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

What are the reasons behind the 502 Bad Gateway error?

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

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

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

How to Troubleshoot a 502 error message

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

Reload the page

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

Clear browser cache

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

Flush DNS cache

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

ipconfig /flushdns

On macOS, you should open the terminal and type:

sudo killall -HUP mDNSResponder

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

sudo killall -HUP mDNSResponder; dns cleared successfully

Things are different in Linux, as different Linux distributions use different DNS services. Some of them are NSCD (Name Service Caching Daemon), dnsmasq, and BIND (Berkeley Internet Name Domain). For an NSCD DNS cache:

sudo /etc/init.d/nscd restart

For a dnsmasq DNS cache:

sudo /etc/init.d/dnsmasq restart

For a BIND DNS cache:

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

If the terminal asks for your password, just enter it.

Change DNS servers

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

If you’re using Cloudflare

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

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

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

Restart PHP

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

Check logs

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

/var/log/nginx

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

/var/log/apache2

Improper firewall configuration

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

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

Third-party plugins & themes

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

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

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

Restart PHP-FPM service

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

sudo service php7.4-fpm status

For SystemD:

sudo systemctl status php7.4-fpm

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

sudo service php7.4-fpm restart

For SystemD:

sudo systemctl restart php7.4-fpm

Timeout issues

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

PHP-FPM timeout is set in pool configuration which is

request_terminate_timeout

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

nginx -s reload

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

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

FAQs

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

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

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

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

Do 502 errors have any impact on website rankings?

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

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

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

Conclusion

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

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

Ошибка 502 Bad Gateway указывает на то, что интернет-сервер вернул недопустимый ответ при попытке доступа к веб-странице.

Однако эта ошибка также может возникать из-за проблем с компьютером.

Вы не уверены, что означает плохой шлюз 502 или как его решить?

Вот пошаговое руководство по устранению ошибки 502 Bad Gateway. Узнайте, что это значит, как определить и как решить.

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

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

Коды состояния HTTP из диапазона 500, такие как 500, 501, 503, 504 и т. д., указывают на ошибки сервера среди этих сетевых сбоев.

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

В зависимости от операционной системы, браузера, веб-сервера и хоста ошибка 502 Bad Gateway может появляться по-разному. Ниже приведены наиболее частые формы временной ошибки HTTP 502 Bad Gateway:

  • Ошибка HTTP 502 Неверный шлюз
  • 502 Ошибка прокси-сервера
  • 502 Плохой шлюз NGINX
  • Ошибка сервера
  • Служба шлюза 502 временно перегружена
  • HTTP 502
  • Временная ошибка 502

Вот пример того, как Google отображает это.

Другие службы, такие как Twitter, могут отображать совершенно другое сообщение в ответ на ошибку 502 Bad Gateway, например «Twitter переполнен». Это кажется немного более удобным для пользователя.

Причины ошибки 502 Bad Gateway

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

  • Из-за внезапного всплеска трафика (перегрузка сервера)
  • Когда брандмауэр блокирует запрос
  • Когда адрес домена не разрешается
  • Время ожидания программного обеспечения сервера (возврат запроса с веб-сервера занимает больше времени, чем предполагалось.)
  • Некоторые расширения браузера также могут иногда приводить к ошибкам, в основном это расширение AdBlock.

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

Если вы пользователь, попробуйте следующее:

Попробуйте перезагрузить страницу.

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

Проверьте, не закрыт ли сайт для других.

Если у вас возникли проблемы с подключением к веб-сайту (по какой-либо причине), вы можете увидеть, возникают ли проблемы только у вас или у других людей. Для этого существует множество инструментов, таких как down.com.

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

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

Ошибка 502 Bad Gateway также может быть вызвана проблемой с вашим браузером. Использование другого браузера, чтобы проверить, работает ли он, — это простой способ проверить это. Google Chrome, Mozilla Firefox, Apple Safari или Microsoft Edge — все это варианты. Если ошибка появляется и в новом браузере, вы будете знать, что это не проблема браузера, и вам следует попробовать другое решение.

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

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

Проверьте расширения браузера

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

Перезагрузите устройства

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

Скорее всего, ваш компьютер или сетевое оборудование (Wi-Fi, маршрутизатор и т. д.) испытывают странные и временные проблемы. Эту проблему можно решить, перезагрузив компьютер и сетевое оборудование.

Изменить DNS-серверы

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

Если вы системный администратор или владелец веб-сайта, попробуйте следующее:

Работает ли внутренний сервер?

  • Проверьте, работает ли внутренний сервер (например, PHP, NodeJS, Tomcat и т. д.)? Если нет, запустите его.
  • Если бэкэнд-сервер работает, может быть, он завис? Или не в состоянии обслужить какой-либо запрос?
  • Может ли веб-сервер общаться с внутренним сервером? Может проблема в брандмауэре?

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

Временно отключите CDN или брандмауэр.

Сети доставки контента (CDN) представляют собой прозрачную основу Интернета для распространения контента. Ошибка 502 bad Gateway может быть вызвана CDN. Вы используете CDN от стороннего сервиса.

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

Подведение итогов 👨‍💻

В этой статье мы рассмотрели, что означает проблема 502 Bad Gateway, наиболее распространенные причины и способы ее решения.

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

When your website experiences a 502 Bad Gateway Error, it can be like solving a mystery. You don’t know what exactly happened or why — all you know is that something’s wrong and you need to fix it.

502-bad-gateway-error

Improve your website with effective technical SEO. Start by conducting this  audit. 

What causes a 502 bad gateway error?

To guide you through the hassle of fixing the dreaded 502 Bad Gateway Error, let’s go over what it exactly is and its most common causes and solutions.

A 502 Bad Gateway Error is a general indicator that there’s something wrong with a website’s server communication. Since it’s just a generic error, it doesn’t actually tell you the website’s exact issue. When this happens, your website will serve an error web page to your site’s visitors, like the photo below.

502 bad gateway error

Picture Credit: Arm Mbed OS

Fortunately, there are seven common and effective solutions for analyzing and fixing most of the causes of 502 Bad Gateway Errors.

The tactics discussed below provide general fixes for 502 Bad Gateway Errors. If you have a WordPress site, this issue may require WordPress-specific solutions.

How to Fix a 502 Bad Gateway Error

  1. Reload the page.
  2. Look for server connectivity issues.
  3. Check for any DNS changes.
  4. Sift through your logs.
  5. Fix faulty firewall configurations.
  6. Comb through your website’s code to find bugs.
  7. Contact your host.

1. Reload the page.

Sometimes server connectivity issues are resolved relatively quickly. Before you dive deep into what’s causing the problem, take steps to ensure that this is actually a major error and not just a blip.

Wait a minute or two. Then reload the page. If the page loads with no error, this might’ve been a temporary connection problem.

If the page is still giving you an error, clear your browser cache and then try refreshing it once more.

If that doesn’t work, move on to investigating the error.

2. Look for server connectivity issues.

Most websites live on multiple servers or third-party hosting providers. If your server is down for maintenance or any other reason, your website could serve visitors a 502 Bad Gateway Error page.

The only way to troubleshoot this issue is to wait for your server to finish maintenance or fix the problem causing the error.

If you don’t want to contact your hosting service, one quick way to make this determination could involve running a ping test to see if messages are reaching your IP.

3. Check for any DNS changes.

If you’ve recently changed host servers or moved your website to a different IP address, it’ll make changes to your website’s DNS server. This could cause your website to serve its visitors a 502 Bad Gateway Error page.

Your website won’t be up and running until these DNS changes take full effect, which can take a few hours.

4. Sift through your logs.

Server logs will provide details about your server’s health and status. Sift through them to uncover and respond to any alarming information.

5. Fix faulty firewall configurations.

Your firewall is your website’s gatekeeper, protecting your site from malicious visitors or distributed denial-of-service (DDoS) attacks.

Sometimes, a faulty firewall configuration will cause your firewall to deem requests from a content delivery network as an attack on your server and reject them, resulting in a 502 Bad Gateway Error. Check your firewall configuration to pinpoint and fix the issue.

6. Comb through your website’s code to find bugs.

If there’s a mistake in your website’s code, your server might not be able to correctly answer requests from a content delivery network. Comb through your code to find bugs or copy your code into a development machine.

It’ll perform a thorough debug process that will simulate the situation that your 502 Bad Gateway Error occurred in and allow you to see the exact moment where things went wrong. 

7. Contact your host.

If you can’t figure out the problem on your own, or if you think your host company is the culprit, give them a call. They may be able to look deeper into what’s going on and shed some light on the situation.

If the issue is on their end, they might be able to easily fix it. If the problem is something related to your website specifically, they might also be able to walk you through the solution.

Improve your website with effective technical SEO. Start by conducting this  audit.  

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

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

  • Http 500 internal server error отсутствует rsa сертификат
  • Http 500 internal server error roblox studio
  • Http 500 internal server error iis
  • Http 500 internal error двач
  • Http 500 internal error dashchan

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

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