Ошибка 502 bad gateway вордпресс

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

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

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

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

Перво-наперво, что во имя вопроса является ошибкой 502 неверного шлюза? Вот небольшой урок о хостинге. Хостинг вашего сайта WordPress обычно включает несколько серверов.

Самая простая настройка может включать от четырех до пяти (иш) серверов, а именно:

  • Сервер приложений, который обрабатывает ваш PHP-код и любой другой динамический контент на вашем сайте.
  • Сервер базы данных, на котором находятся ваши базы данных
  • Обратный прокси-сервер, например Nginx и Apache, который контролирует, какие HTTP-запросы идут куда
  • Веб-сервер, на котором хранятся все ваши статические файлы, такие как изображения, CSS и JavaScript.
  • CDN (дополнительный сервер производительности)

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

Затем резервный прокси-сервер направляет запросы на соответствующие серверы. Например, запросы данных, хранящихся в вашей базе данных, направляются на сервер базы данных. Запросы статических файлов направляются на веб-сервер, а запросы, требующие PHP, обрабатываются сервером приложений.

Затем каждый сервер отправляет данные обратно на обратный прокси-сервер, который затем отправляет данные в ваш браузер, и ваш сайт загружается. Просто как A, B, C – пусть вас не смущают такие жесткие слова, как обратный прокси.

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

Животное самых разных форм

Ошибка 502 неверного шлюза может принимать различные формы, например:

  • Ошибка 502
  • 502 Плохой шлюз NGINX
  • 502 Ошибка прокси
  • 502 Сервис временно перегружен
  • Ошибка HTTP 502 Плохой шлюз
  • 502 Это ошибка. Сервер обнаружил временную ошибку и не смог выполнить ваш запрос. Повторите попытку через 30 секунд. Это все, что мы знаем.

Что вызывает ошибку 502 Bad Gateway?

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

  • Ваш исходный сервер может быть перегружен из-за увеличения трафика
  • Автономный сервер бросит вам в лицо ошибку 502 bad gateway
  • Неправильная конфигурация сервера, которая может быть отложена из-за ряда причин, таких как человеческая ошибка, особенно когда ваш хост перемещает серверы
  • Проблемы с вашей сетью доставки контента (CDN)
  • Неправильный кеш браузера
  • Проблемы с DNS
  • Неправильный код PHP из-за проблемного плагина или темы

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

При этом давайте устраним ошибку 502 неверного шлюза на вашем сайте WordPress.

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

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

1 Обновите / перезагрузите свой сайт

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

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

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

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

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

Вы не можете исправить ошибку 502 неверного шлюза даже после обновления браузера? Если это так, выполните аппаратное обновление в своем браузере (CTRL + F5 в системах Windows и CMD + CTRL + R в системах OS X). Избавляется ли выполнение аппаратного обновления от неприятной ошибки, связанной с ошибкой 502 неверного шлюза? Нет?

Что ж, вы можете попробовать очистить кеш браузера напрямую, используя советы, которые мы приводим в том, как очистить кеш WordPress. Устранена ли неприятная ошибка после очистки кеша? Если так, прекратите читать и танцуйте весело. Даже сальто назад. Шутки в сторону.

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

3 Временно отключите CDN

Используете ли вы сеть доставки контента, такую ​​как CloudFlare, KeyCDN или другой CDN для WordPress? Сети CDN обычно направляют трафик вашего сайта на свои серверы, чтобы предложить вам лучшую производительность и безопасность сайта.

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

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

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

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

4 Проблемы с DNS

DNS (сокращение от системы доменных имен) – это то, как доменные имена (например, wpexplorer.com) совпадают с соответствующими IP-адресами. Если что-то не так с настройками DNS, вы можете ожидать ошибку 502 плохого шлюза среди других проблем.

Недавно переехали на нового хозяина? Перенос включает перенастройку ваших DNS-серверов. Распространение DNS занимает время, иногда до 48 часов и более.

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

И поскольку мы говорим о DNS, вы также можете попробовать очистить локальный кеш DNS. Для пользователей Windows откройте командную строку (cmd.exe) и выполните следующую команду: ipconfig / flushdns. Как пользователь Mac OS X запустите dscacheutil -flushcache в командном терминале.

5 Проверьте свою тему и плагины.

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

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

6 Плагины для устранения неполадок

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

Ну все просто. Войдите в свой корневой каталог WordPress (обычно это public_html, но может быть что-то еще, в зависимости от того, где вы установили свой сайт), используя FTP-приложение, такое как Filezilla или File Manager в cPanel.

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

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

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

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

Переименуйте plugins.old обратно в плагины и войдите в панель администратора WordPress. Пора найти проблемный плагин.

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

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

7 Устранение неполадок активной темы

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

Проверка, является ли ваша тема проблемой, немного отличается от плагинов для устранения неполадок. Давай покончим с этим.

Войдите в корневой каталог WordPress через FTP или файловый менеджер. Затем перейдите к wp-content> themes и найдите свою активную тему.

Переименуйте папку активной темы во что-то вроде total.old. Это отключит активную тему и активирует тему WordPress по умолчанию.

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

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

Если ошибка исчезнет, ​​обратитесь к разработчику вашей темы за дополнительной помощью или приобретите профессиональную тему, такую ​​как наша собственная Total.

8 Если проблема не исчезнет, ​​обратитесь к хозяину.

По-прежнему не можете исправить ошибку 502 плохого шлюза на вашем сайте WordPress даже после попытки всех вышеперечисленных решений?

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

Заключение

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

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

Источник записи: https://www.wpexplorer.com

Вы когда-нибудь видели очень раздражающую и разочаровывающую ошибку 502 на сайте WordPress? Да, я думаю, мы все столкнулись с проблемой. Знаете ли вы, что означает ошибка 502 «Bad Gateway»? Вы знаете, как решить проблему? В этом сообщении в блоге мы предоставим вам подробную информацию о ошибке «502 Bad Gateway» в WordPress и расскажем вам, как устранить ошибку «502 Bad Gateway» в WordPress. 

Ошибка 502 Bad Gateway — это код состояния HTTP, который означает, что один сервер в Интернете получил неверный ответ от другого сервера. Техническими словами 502 Bad Gateway означает, что сервер прокси (шлюза) не смог получить действительный или любой ответ от восходящего сервера.

В официальной документации W3.org указано, что коды состояния HTTP, начинающиеся с 5 (5xxx), относятся к ошибкам, возникающим при неправильной связи между несколькими серверами.

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

502 Bad Gateway — Разнообразие ошибок

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

  • “502 Bad Gateway”
  • “Error 502”
  • “HTTP Error 502 – Bad Gateway”
  • “502 Proxy Error”
  • “HTTP 502”
  • “502 Service Temporarily Overloaded
  • “502 Server Error: The server encountered a temporary error and could not complete your request”
  • “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.”
  • Пустой белый экран

Как исправить ошибку 502 Bad Gateway (3 возможных решения)

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

1. Проверьте свой сервер

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

Если вы видите ошибку, как показано на рисунке, скорее всего, ошибка находится на вашем веб-сервере.
Давайте проверим вашу конфигурацию веб-сервера, в этом случае на сервере работает Nginx. WordPress работает на PHP и MySQL. Итак, в nginx нам нужно проверить, как обрабатываются файлы PHP. Найдите “location ~ .php$” в вашем блоке сервера nginx.

ssh @ your _ip -p7022

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

Согласно конфигурации nginx, как показано на рисунке, файлы PHP обрабатываются fastcgi, который выполняется на порте 9000.
Давайте проверим, что работает на порту

netstat -pltn | grep 9000

Если вы не видите результата после выдачи команды, значит процесс умер. Вот почему вы видите ошибочную ошибку шлюза 502.

В последних CentOS и Ubuntu вы можете вызвать следующую команду, чтобы увидеть, от чего должен запускаться процесс:

systemctl list-unit-files | grep fpm

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

Выполните эту команду для запуска службы:

systemctl start php7.0-fpm

Теперь перейдите в свой веб-браузер и проверьте свой сайт.

Если вы используете CloudFlare и видите ошибку 502 Bad Gateway, как показано на рисунке ниже, скорее всего, ваш веб-сервер не работает. Вы можете попробовать перезапустить apache или nginx, в зависимости от того, какой веб-сервер вы используете.

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

2. Очистите кеш.

Если первое решение было выполнено, но вы по-прежнему видите ошибку плохого шлюза 502, ваш веб-браузер все еще полагается на свой кеш. Мы должны сообщить браузеру загрузить последнюю версию с сайта. Мы можем сделать это, нажав Ctrl+F5 на клавиатуре (Windows/Linux) или кнопку Shift + Reload на панели инструментов (браузер Safari) или CMD+Shift+R (Chrome и Firefox для пользователей Mac).

3. Отключить CDN

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

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

4. Проверьте свои скрипты.

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

5. Проверка плагинов и тем

Устранение неполадок, вызвавших ошибку, очень просто. Даже если у нас нет доступа к нашему серверу WordPress, мы можем отключить все плагины сразу, переименовав каталог плагинов. Для этого подключитесь к серверу с помощью SSH. Обратите внимание, что вы также можете сделать это с помощью FTP-клиента, например FileZilla.

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

Давайте создадим каталог плагинов и переместите плагин. Это автоматически включит плагин.

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

Иногда устранение ошибок WordPress проще, чем мы могли бы подумать. Но в какой-то момент это может быть очень сложно решить.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

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

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

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

Если сервер точно отвечает на запросы, он получает запрошенный контент. В противном случае появится экран 502 Bad Gateway Error.

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

  • Сервер баз данных для баз данных WordPress,
  • Сервер приложений для запуска PHP и другого контента, связанного с приложениями,
  • Обратный прокси-сервер, отвечающий за Nginx, Apache, Varnish,
  • Веб-сервер для обслуживания файлов веб-сайта.

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

Если какой-либо из этих серверов отправит неверный ответ, обратный прокси-сервер вернется в браузер и отобразит ошибку 502 Bad Gateway.

Мы часто видим ошибку 502 Bad Gateway Error на разных сайтах по-разному, но все они указывают на одно и то же: сервер не может отвечать на запросы. Давайте посмотрим на некоторые примеры, которые показывает эта ошибка.

  • «502 Неверный шлюз»
  • «Ошибка HTTP 502, плохой шлюз»
  • «Служба 502 временно перегружена»
  • «Ошибка 502»
  • «502 Ошибка прокси-сервера»
  • «HTTP 502»
  • «502 Плохой шлюз NGINX»
  • «Ошибка сервера 502: сервер обнаружил временную ошибку и не смог выполнить ваш запрос»
  • «502. Это ошибка. Сервер обнаружил временную ошибку и не смог выполнить ваш запрос. Повторите попытку через 30 секунд. Это все, что мы знаем.»

502 плохой шлюз nginx

Twitter отображает 502 Bad Gateway Error в более дружелюбной форме.

твиттер ошибка 502

Google отображает ошибку 502 Bad Gateway Error с предложением повторить попытку через некоторое время.

ошибка гугл 502

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

Почему в WordPress возникает ошибка 502 Bad Gateway?

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

  • Ваш сервер занят другими задачами или страдает от всплесков трафика
  • Исходные серверы не отвечают или недоступны
  • Ошибки в базе
  • Проблема с обратным прокси-сервером
  • Поврежденные PHP-скрипты в файлах WordPress
  • WordPress CDN капризничает
  • Проблемы с DNS

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

Как 502 Bad Gateway влияет на SEO

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

Исправить ошибку 502 Bad Gateway в WordPress

Это самые простые способы исправить ошибку 502 Bad Gateway в WordPress.

  1. Проверить хостинг-сервер
  2. Перезагрузить веб-страницу
  3. Очистить кеш браузера
  4. Проверить проблемы с DNS
  5. Очистить кеш DNS
  6. Отключить CDN/брандмауэр
  7. Аудит Темы/Плагины
  8. Проверить журналы ошибок
  9. Установить время ожидания PHP
  10. Проверьте пользовательские сценарии

1. Проверьте хостинг-сервер

Первое, что вам нужно, это проверить, отвечает ли ваш веб-сервер или нет. Не всегда с вашим сайтом WordPress происходит что-то ужасное. Самый простой способ определить, является ли ваш сервер виновником, — запустить онлайн-сканирование. Посетите site24x7 и введите URL своего сайта.

онлайн сканирование сайта

Несколько мест пропингуют ваш сервер и покажут вам статистику, такую ​​​​как время загрузки, потеря пакета и время ответа.

Еще один способ проверить скорость отклика вашего веб-сервера — пропинговать его вручную с помощью SSH. Просто войдите в терминал SSH и выполните следующую команду:

  1. пинг ( IP сервера )

Теперь замените «IP-адрес сервера» на IP-адрес вашего сервера.

ip сервера пинга

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

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

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

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

2. Перезагрузите веб-страницу

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

Кроме того, подтвердите, не работает ли веб-сайт для вас или всех остальных. Чтобы сделать это, проверьте URL-адрес в разделе « Вниз для всех» или «Только для меня».

вниз для всех или только для меня

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

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

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

Допустим, вы зашли в другой браузер, и веб-страница загрузилась нормально. Зная, что ваша веб-страница загружается правильно, вы возвращаетесь к браузеру по умолчанию, но проблема остается. Это потому, что ваш браузер отображает кешированную копию этой веб-страницы. Чтобы это исправить, очистите кеш браузера с помощью Ctrl+Shift+Del (для Windows) или Shift+Cmd+Del (для Mac).

очистить данные просмотра

4. Проверьте проблемы с DNS

Система доменных имен (DNS) — это способ связать доменное имя с IP-адресом. Если домену не удается преобразовать правильный IP-адрес, это может вызвать ошибку 502 Bad Gateway. Обычно это происходит при переносе сайта WordPress на новый хост, который требует изменений в сервере имен DNS.

Для распространения изменений DNS может потребоваться от 24 до 36 часов. Если вы попытаетесь получить доступ к своему сайту в течение этого периода, вы можете получить ошибку WordPress 502 Bad Gateway.

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

Вы можете очистить кеш DNS из командной строки Windows. В Windows запустите команду ipconfig/flushdns, чтобы очистить кеш DNS. В Mac запустите команду как dscacheutil -flushcache в окне терминала.

очистить кеш днс

6. Отключить CDN/брандмауэр

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

CDN обслуживает статический контент веб-сайта и быстрее загружает ваш сайт для глобальной аудитории. Напротив, брандмауэр защищает ваш сайт от DDoS и других онлайн-атак. Однако CDN/брандмауэр может быть одной из причин ошибки 502 Bad Gateway в WordPress из-за дополнительного слоя между сервером и браузером.

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

7. Аудит тем/плагинов

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

Начните с деактивации всех плагинов с FTP. Просто войдите в свой корневой каталог, где установлены ваши файлы WordPress, то есть в папку public_html, перейдите в wp-content → plugins и переименуйте папку plugins, чтобы она стала недоступной для вашего сайта.

переименовать директорию плагина

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

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

переименовать директорию темы

На следующем шаге обновите свой веб-сайт, и если вы увидите белый экран вместо ошибки, проблема была вызвана вашей темой. Войдите в свой wp-admin и активируйте тему WordPress по умолчанию.

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

Журналы WordPress полезны, когда дело доходит до устранения ошибок. Вы можете включить журналы ошибок, добавив следующий код в файл wp-config.php.

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

Журналы находятся внутри папки wp-content. Если вы являетесь пользователем gohost, вы можете воспользоваться интегрированным инструментом мониторинга New Relic для точного и всестороннего анализа.

новая реликвия в облаках

9. Установите время ожидания PHP

Когда PHP достигает максимального времени в конфигурации сервера для выполнения скрипта, он показывает ошибку. Иногда это может вызвать ошибку WordPress 502 Bad Gateway. Чтобы этого избежать, просто увеличьте максимальное значение времени выполнения. По умолчанию установлено значение 300 секунд, что составляет 5 минут.

10. Проверьте пользовательские сценарии

Мы создаем пользовательские функции и темы в WordPress. Иногда наш веб-сервер не обрабатывает эти пользовательские функции. Кроме того, вызов сторонних API, таких как Google reCAPTCHA, который генерирует длинные токены, может вызвать нагрузку на сервер и показать ошибку 502 Bad Gateway Error.

Резюме

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

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

Часто задаваемые вопросы

В: Что вызывает ошибку 502 Bad Gateway?

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

В: Как исправить ошибку Google 502?

О: Вы можете исправить ошибку 502 Bad Gateway, выполнив следующие действия:

  • Проверить хостинг-сервер
  • Перезагрузить веб-страницу
  • Очистить кеш браузера
  • Проверить проблемы с DNS
  • Очистить кеш DNS
  • Отключить CDN/брандмауэр
  • Аудит Темы/Плагины
  • Проверить журналы ошибок
  • Установить время ожидания PHP
  • Проверьте пользовательские сценарии

В: Является ли 502 Bad Gateway вирусом?

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

Ошибка 502 WordPress bad gateway - причины, как исправить

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

502 вордпресс

Ошибка 502 генерируется сервером и сигнализирует, что запрос для страницы, сценария или процесса занял слишком много времени для завершения и был принудительно отменен. Главная причина ошибки 502 заключается в нехватке ресурсов на сервере – у PHP-движка закончилась память. Для сайтов на WordPress ошибка появляется при обновлении движка и плагинов или при сохранении больших записей. Это может происходить из-за следующих проблем:

  • Очень большой код – много установленных плагинов или очень сложных модулей;
  • Чересчур много посетителей на сайте;
  • Малое время выполнения скриптов.

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

Как устранить ошибку WordPress 502 bad gateway

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

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

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

WordPress потребляет большое количество ресурсов сервера, особенно если вы используете множество плагинов. Чтобы проверить, вписываетесь ли вы в установленный тариф, в админке зайдите в меню «Внешний вид — Редактор», из списка шаблонов выберите шаблон подвала (файл footer.php) и добавьте туда строку кода:


<?php include('adplus-right-bottom.html'); ?>

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

запрос

iPipe – надёжный хостинг-провайдер с опытом работы более 15 лет.

Мы предлагаем:

  • Виртуальные серверы с NVMe SSD дисками от 299 руб/мес
  • Безлимитный хостинг на SSD дисках от 142 руб/мес
  • Выделенные серверы в наличии и под заказ
  • Регистрацию доменов в более 350 зонах

fix 502 bad gateway error in wordpress

WordPress is easy, but it is equally frustrating to troubleshoot the errors that can occur at any time. Just like prescribing the right medicine to fight disease effectively, you need complete knowledge about that disease. Knowing the error and its causes are essential before troubleshooting it.

When your website has the 502 Bad Gateway Error, it’s like solving a mystery. You don’t know what exactly happened or why you expect that something is wrong, and you need to fix it. In this article, I’ll tell you about the 502 Bad Gateway Error and how you can fix it in your WordPress.

  • What Is the 502 Bad Gateway Error?
  • Why Does 502 Bad Gateway Error Occur?
  • How Does 502 Bad Gateway Affect the SEO
  • Fix the “502 Bad Gateway” Error in WordPress

What Is the 502 Bad Gateway Error?

To understand the 502 Bad Gateway Error, you should know how a browser loads data from the server. When a user visits a website, the server sends a request to fetch the data required to display the content in the browser.

If the server responds accurately to the requests, it receives the requested content. Otherwise, the 502 Bad Gateway Error screen comes up.

WordPress websites run on multiple servers allocated to a specific task. For example:

  • Database server for WordPress databases,
  • Application server to run PHP and other app-related content,
  • The reversed proxy server responsible for Nginx, Apache, Varnish,
  • Web server to serve website files.

The multiple servers together can complicate the way the browser handles the requests. Upon receiving the request, the reversed proxy server fetches data from origin servers like a database server, application server, and web server.

If any of these servers send an invalid response, the reversed proxy server returns to the browser and displays a 502 Bad Gateway Error.

We often see 502 Bad Gateway Error differently on different websites, but they all point to the same: the server could not respond to the requests. Let us look at some of the examples this error shows.

  • “502 Bad Gateway”
  • “HTTP Error 502 Bad Gateway”
  • “502 Service Temporarily Overloaded”
  • “Error 502”
  • “502 Proxy Error”
  • “HTTP 502”
  • “502 Bad Gateway NGINX”
  • “502 Server Error: The server encountered a temporary error and could not complete your request”
  • “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.”

502 bad gateway nginx

Twitter displays 502 Bad Gateway Error in a friendlier way.

twitter 502 error

Google displays a 502 Bad Gateway Error with the suggestion of trying again after some time.

google 502 error

Now that we have understood what is 502 Bad Gateway Error is and how different websites display it. Let us move ahead and explore what causes this error and how can we fix it in WordPress?

Why Does 502 Bad Gateway Error Occur in WordPress?

We get a 502 Bad Gateway Error when the server fails to respond accurately and returns the request with invalid information. However, there are other possibilities as well, and knowing them is crucial if you wish to troubleshoot this error effectively.

  • Your server is busy with other tasks or hit by traffic spikes
  • Origin servers are unresponsive or inaccessible
  • Errors in the database
  • Problem with the reverse proxy server
  • Corrupt PHP scripts in WordPress files
  • WordPress CDN is acting up
  • DNS issues

All of the above possibilities can result in WordPress 502 Bad Gateway Error. However, troubleshooting any error gets trickier if you do not know the elements involved in triggering that error.

How Does 502 Bad Gateway Affect the SEO

If your site often goes down because of the 502 Bad Gateway error, it will also affect your site’s traffic. Imagine your visitor gets this error on your site; he might not visit your site next time. Similarly, it will impact the crawling and indexing of your site due to unavailability. Hence, you will lose your organic ranking and traffic.

These are the easiest methods to fix the 502 Bad Gateway Error in WordPress.

  1. Check Hosting Server
  2. Reload Web Page
  3. Clear Browser Cache
  4. Check DNS Issues
  5. Clear DNS Cache
  6. Disable CDN/Firewall
  7. Audit Themes/Plugins
  8. Check Error Logs
  9. Set PHP Timeout
  10. Check Custom Scripts

1. Check Hosting Server

The first thing you need is to check if your web server is responsive or not. It is not always something terrible happening to your WordPress website. The easiest way to determine if your server is the culprit is to run an online scan. Visit site24x7 and enter your site URL.

online site scan

The multiple locations will ping your server and show you the stats like Load time, Package Loss, and Response time.

Another way to check your web server’s responsiveness is to ping it manually using SSH. Simply access the SSH terminal and run the following command:

ping (server IP)

Now, replace “server IP” with your server IP address.

ping server ip

If your server is responsive, it will show the ping on each interval.

Sometimes any query or task takes more time than usual; the server cancels it and returns with a 502 Bad Gateway Error. It is common in shared hosting, and the provider kills the script to avoid any negative impact on other websites hosted on the same server.

If you are using Cloudways, you will have a low chance of getting this error. That is because you are the only owner of your server and control the websites hosted on it, and we use a powerful stack that can cope with a load on servers.

However, if you still encounter such issues, Cloudways’ 24/7 live chat support can help you recover from this situation.

2. Reload Web Page

Sometimes just by reloading the web page, you can save hours’ worth of troubleshooting. It is possible that you get an overloaded server for some time and when you check back in a minute or so, it brings back on.

Also, confirm if the website is down for you or everyone else. Test the URL on Down for Everyone or Just Me to do this.

down for everyone or just me

If the website is up for everyone else, then the problem is at your end. Try switching the web browser.

3. Clear Browser Cache

The browser caches or stores site data so the next time the user visits, it does not have to repeatedly download the same static content. It is an effective way of utilizing resources but has some drawbacks.

Let’s say you went to a different browser and the web page loaded just fine. Knowing that your web page loads correctly, you return to your default browser, but the issue persists. That is because your browser displays the cached copy of that web page. To fix that, clear your browser cache via Ctrl+Shift+Del (for Windows) or Shift+Cmd+Del (for Mac).

clear browsing data

4. Check DNS Issues

A Domain Name System (DNS) is a way of linking a domain name with an IP address. If the domain fails to resolve to the correct IP, it can trigger a 502 Bad Gateway Error. It commonly occurs while migrating a WordPress site to a new host that requires changes in the DNS name server.

The DNS changes can take between 24 to 36 hours to propagate. If you try to access your site during this period, you might get a WordPress 502 Bad Gateway Error.

5. Clear DNS Cache

You can clear the DNS cache from Windows Command Prompt. In Windows, run ipconfig/flushdns command to clear the DNS cache. In Mac, run the command as dscacheutil -flushcache inside the terminal window.

clear dns cache

6. Disable CDN/Firewall

If you use a CDN service or a firewall on your website, their servers may be acting up.

A CDN serves static website content and loads your site to a global audience faster. In contrast, a firewall protects your site against DDoS and other online attacks. However, A CDN/firewall can be one of the reasons for the 502 Bad Gateway Error in WordPress due to an extra layer between the server and browser.

To cross this from your list of possible causes, simply disable your CDN/firewall and then try to access your website. If the website loads correctly, then you have caught the culprit. You just need to contact CDN/firewall service provider to get it fixed.

7. Audit Themes/Plugins

A fully functional WordPress site is nearly impossible without adding themes and plugins. But they can also become one of the reasons for the 502 Bad Gateway Error. The problem lessens with the best wordpress plugins, but the threat of 502 error lurks with them as well. If they are not well-written, they can cause issues with your web server or take too long to process the requests. The problem can arise even if you work with the best wordpress themes for your website.

Start by deactivating all the plugins from FTP. Simply access your root directory where your WordPress files are installed, i.e., public_html folder, navigate to wp-content → plugins, and rename the plugins folder so it will become inaccessible to your site.

rename plugin directory

Now check your website to see if it loads correctly, then you can start activating plugins one by one until you find the one causing 502 Bad Gateway Error.

Look for a defective theme if you don’t find any faulty plugins. Go to your wp-content folder, navigate to themes and rename your activated theme to deactivate it. But remember, removing your theme might not be suitable as uploading it again can lose custom styling.

rename theme directory

In the next step, refresh your website and if you see a white screen instead of an error, then your theme was causing the issue. Log in to your wp-admin and activate the default WordPress theme.

8. Check Error Logs

WordPress logs are useful when it comes to troubleshooting errors. You can enable the error logs by adding the following code inside the wp-config.php file.

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

The logs are located inside the wp-content folder. If you’re a Cloudways user, you can take advantage of the integrated monitoring tool New Relic for precise and comprehensive analysis.

new relic in cloudways

9. Set PHP Timeout

When PHP reaches the maximum time in server configuration to execute a script, it shows an error. It can sometimes trigger WordPress 502 Bad Gateway Error. To avoid this, simply increase the maximum execution time value. It is set to 300 seconds by default, which is 5 minutes.

10. Check Custom Scripts

We create custom functionality and themes in WordPress. Sometimes, our web server doesn’t process these custom functionalities. Also, calling third-party APIs, such as Google reCAPTCHA, which generates long tokens, can stress the server and show the 502 Bad Gateway Error.

Summary

After reading this article, I hope 502 Bad Gateway Error will not look so scary the next time you see it. The troubleshooting is easy if you can predict the source and use the techniques listed in this article to fix it.

You can still fix the WordPress 502 Bad Gateway Error just by reloading and clearing the browser cache but not every day is sunny, so it is wise to prepare for the dark.

Frequently Asked Questions

Q: What causes a 502 Bad Gateway Error?

A: When you get an invalid response on your browser when trying to visit your site causes the 502 Bad Gateway Error.

Q: How do I fix Google 502 error?

A: You can fix the 502 Bad Gateway Error by following these methods:

  • Check Hosting Server
  • Reload Web Page
  • Clear Browser Cache
  • Check DNS Issues
  • Clear DNS Cache
  • Disable CDN/Firewall
  • Audit Themes/Plugins
  • Check Error Logs
  • Set PHP Timeout
  • Check Custom Scripts

Q: Is 502 Bad Gateway a virus?

A: No, it’s not a virus. You get the 502 error because of the bugs in your PHP. Server configuration or network error among servers can cause 502 Bad Gateway.

Share your opinion in the comment section.
COMMENT NOW

Share This Article

Customer Review at

“Beautifully optimized hosting for WordPress and Magento”

Arda Burak [Agency Owner]

Ibad Ur Rehman

Ibad Ur Rehman is a WordPress Community Manager at Cloudways. He likes to explore the latest open-source technologies and to interact with different communities. In his free time, he likes to read, watch a series or fly his favorite Cessna 172SP in X Plane 11 flight simulator.

If you’re a site owner, few things make your stomach drop like trying to load your website only to receive a cryptic error message. You’re probably familiar with the 404 Page Not Found error, but what about the 502 Bad Gateway issue?

Fortunately, the 502 error is usually easy to fix. Once you’ve found the source of the problem, resolving it is something most WordPress users can do on their own, without advanced technical knowledge.

In this article, we’ll cover the different causes of a 502 error. Then, we’ll show you how to isolate and resolve the issue.

What causes the “502 Bad Gateway” error in WordPress?

The 500 series error codes, also known as HTTP status codes, are used to diagnose communication errors between a web browser and website server. Essentially, when a browser tries to connect to a website, it contacts the website’s server to request access. If this request cannot be fulfilled, then a 500 series error is usually returned, explaining what went wrong. 

Error 502 indicates a bad gateway. This is when a server attempts to access another server but is unable to complete the request. 

Usually the error is not with the website itself, but the server being accessed. The website is simply behaving as a middleman, or “gateway,” but is unable to deliver the requested data. 

If your WordPress site is being affected by a persistent 502 error, it may be a server error outside of your immediate control. This error can make your site inaccessible to visitors. It can also negatively impact your search rankings, as search engines may be unable to access your site.

While this is normally an issue with your host’s servers rather than your website, there are still some things you can do to fix the problem. In this next section, we’ll cover some possible solutions.

How to fix the “502 Bad Gateway” issue in WordPress

Before reaching out to your host to see if they can resolve the 502 Bad Gateway error, there are some troubleshooting steps you can take to rule out an issue on your end. If these actions help you fix the error, you might want to keep an eye out for repeat issues. If your site is frequently plagued by the 502 Bad Gateway error, you may want to consider upgrading your hosting services.

1. Refresh the page

As with most server issues, simply refreshing the page is always worth a try. If the error was very temporary or just a fluke, it might go away with a refresh. 

A temporary blip or loss of service from an upstream server might resolve itself, allowing for the connection to complete on the next attempt. Sometimes a spike in traffic or loss of connection at the target server can also cause issues. As you’re troubleshooting, you may want to refresh every so often to see if the error persists. 

If refreshing the page solves the problem, it’s safe to assume that the source of the cause was your host. These issues usually resolve themselves quickly.

2. Clear your cache and DNS

On rare occasions, a full cache on the client’s end can simulate server errors, as it’s unable to receive new data as requested. While this is unlikely to return a 502 Bad Gateway error, clearing the cache is a quick and easy fix that can help you rule out the issue. 

Let’s look at how to clear the cache in Google Chrome. Most other browsers will follow a similar process.

First, click on the three-dot icon in the top right corner of the browser window and select Settings. Then, navigate to Security and Privacy on the left.

security and privacy settings in Chrome

Here, select Clear browsing data. A popup window will appear. You’ll want to select All time as the time range, and check the box for Cached images and files.

options for clearing your browser cache in Chrome

Then, just click on the Clear data button and your cache will be emptied. This will free up space for new data.

You may also want to check your Domain Name System (DNS). Like your browser cache, clearing your DNS could be a quick fix if there’s an issue with an IP address.

To clear your DNS, simply open the command prompt and type in the following command:

C:/Users/example>
C:/Users/example>ipconfig /flushdns

command prompt for clearing DNS

After clearing your cache and DNS, try refreshing the page to see if the problem has been resolved. If it’s still there, you can move on to the next method. 

3. Deactivate your plugins and theme

If the 502 Bad Gateway error cropped up after installing a new theme or plugin, it’s possible that one of these programs could be the culprit. A poorly coded or incompatible plugin could cause a conflict that results in a server being slow or unable to communicate.

To find out if this is the case, you’ll need to deactivate your plugins. If you still have access to your site, go to your WordPress admin area and navigate to Plugins. Then, select and deactivate any new plugins you’ve installed:

deactivating WordPress plugins

Alternatively, you can deactivate all of your plugins at once to see if the issue resolves itself. If it does, you’ll have to reactivate your plugins one at a time in order to see which one is acting up.

If you’re unable to access your WordPress admin dashboard, you’ll need to go through a backdoor to manually deactivate your plugins. You have two options: connect to your website via the File Manager in your hosting account, or use a File Transfer Protocol (FTP) client like FileZilla.

We’ll be using FileZilla to show you how to connect to your site’s back end and deactivate your plugins. You’ll need to enter your credentials, including username and server address. You can obtain this information from your hosting account.

Once you’ve connected to your site, you’ll need to navigate to the root folder. This contains all of your site’s files, and is normally called www, public, or public_html

Then, open your wp-content folder and locate the plugins folder.

wp-content/plugins folder via FTP

Next, rename the folder from plugins to something else, like plugins_old. This will break the pathway and all plugins on your site will be deactivated. 

Now, try to refresh your page. If the issue hasn’t been resolved, then your plugins are not the culprit and you can rename the folder back to plugins to reestablish the pathway. 

If deactivating the plugins resolves the issue, you’ll need to find out which one is at fault. To do this, rename the plugins folder back to its original name. Then, rename the folders for the individual plugins and keep refreshing the page until you find which one is causing the error.

renaming a plugin folder in FileZilla

Renaming each individual folder will break the pathway to just one plugin, rather than all of the plugins at once. Once you have identified the faulty plugin, you can access your WordPress admin dashboard to address it accordingly. For instance, you might decide to delete the plugin and install an alternative.

You can follow a similar procedure to check your themes. These are located in the themes folder within wp-content

If the problem persists after deactivating your plugins and theme, you can rule out bad code as the cause. Let’s look at a few other possible solutions. 

4. Check your updates

WordPress developers are constantly updating plugins and themes to fix bugs, improve features, and solve security issues. It’s crucial to keep your site updated not only for security, but also to avoid compatibility issues.

Some themes and plugins are only designed to be compatible with certain versions of WordPress. When installing a new tool, you’ll want to check the required WordPress version.

In the example below, you can see that a WordPress version older than 5.0 or newer than 5.9.1 may not be compatible with the plugin.

Akismet plugin page showing WordPres requirements

This could lead to unexpected behavior from the plugin. Incompatibility issues can cause crashes, long loading times, and time outs that could result in the 502 error.

You can check your current version of WordPress by navigating to Home → Updates in your dashboard.

available WordPress updates

While you’re here, you can run any necessary updates. You might also want to go to your Plugins page to make sure that all of your software is up to date. 

5. Disable the CDN or firewall

If you’re using a content delivery network (CDN) for WordPress, this may increase the chance of a 502 Bad Gateway error as data is being transmitted from and through multiple servers. If there’s a problem with any of these gateways, it could result in an error.

To rule this out, you can disable your CDN to see if there are any changes. If you’re using a plugin to integrate a CDN, simply deactivate that plugin as shown above. If your CDN comes with its own page on your dashboard, there’s likely a setting that allows you to disable it directly.

Security services like firewalls can also cause the 502 Bad Gateway error. These extra layers of security often rely on additional gateways which can fail or delay the request long enough to time out and cause an error. Turning off your firewall temporarily can help you rule out this as a cause.

6. Contact your hosting provider

If none of the above solutions seem to solve the problem, it’s likely that the cause is coming from a hosting server. Try contacting your hosting provider to see if they’re aware of any issues or outages that could be affecting your site. It may be as simple as a server overload or scheduled maintenance. Additionally, a power outage may temporarily affect the service. 

Remember that the 502 Bad Gateway error can shut down traffic and negatively impact your site’s search engine rankings. If the source of the problem is your host, and the issue occurs often or for extended periods of time, you may want to consider more reliable hosting options to avoid future problems. 

7. Restore a backup

In the event that you can’t find a solution or your host is unable to identify any issues on their end, you can try restoring a backup of your website. If the backup does solve the problem, you’ll need to do some detective work to find out what’s causing the error. This means you’ll need to track any changes you’ve made since the last backup.  

As you can imagine, this may be a little time-consuming. Fortunately, you can use a powerful tool like Jetpack Backup to streamline the process. This user-friendly plugin automatically creates backups that you can revert to for any reason. 

Moreover, Jetpack comes with an activity log that tracks every change you make to your site. This way, you can easily identify any recent changes that may have caused the 502 Bad Gateway error.

How to avoid the 502 status error in the future

As we have seen, the 502 status error can make your site inaccessible, which can harm your search rankings and conversions. Fortunately, there are steps you can take to prevent bad gateway errors in the future. Let’s look at some effective precautions. 

1. Vet new plugins and themes

Whenever you add a new plugin or theme to your site, you’ll want to vet it for quality and compatibility. It’s important to make sure that any code you’re adding to your site is coming from a reputable source. You may also want to check the reviews for any known issues. 

Some themes and plugins are only compatible with certain versions of WordPress. Ideally, you’ll only install plugins that are regularly updated.

Keeping your WordPress core, plugins, and themes up to date is also important. Updates usually fix bugs and gaps in security that can cause a number of issues. 

Outdated plugins may lose compatibility with newer versions of WordPress, which can lead to errors on your site. Therefore, you may want to enable auto-updates on your site to avoid issues in the future. 

2. Upgrade to a more powerful hosting solution

One of the most important things you can do to prevent the 502 Bad Gateway error is to ensure that you have adequate resources for your site. 

If your growing website is receiving more and more traffic every day, you may need to upgrade your tier of service to meet these demands. If your hosting server or allocation on that server is overloaded, requests are much more likely to time out and cause the 502 Bad Gateway error. 

Therefore, you might want to upgrade to a more advanced tier. Alternatively, you might consider switching to a different hosting plan, like dedicated or Virtual Private Server (VPS) hosting. 

3. Check your WordPress error logs

If you encounter the 502 Bad Gateway error intermittently and have not been able to nail down the cause of the problem, checking your error logs may help give you some clues. For example, if the error occurs at your highest traffic times, it’s likely that these spikes are overloading the server. 

You can find your error logs in the same directory as your themes and plugins. Connect to your site via FTP or the File Manager in your hosting account, and open the wp-content folder. Here, you’ll see a file called debug.log

finding the WordPress debug log

If you can’t find this file, you may need to activate your log errors. You can then open the file to find and fix the error.

By practicing safe habits and being aware of changes to your site, you can prevent many connection errors. As always, regular backups offer peace of mind and enable you to rule out errors on your end. Having a suitable host is also important for handling all of your traffic and maintaining quick load times.

There’s no such thing as being too prepared

As we’ve seen, the 502 Bad Gateway error can have a negative impact on your site’s SEO and availability. Therefore, it’s important that you know how to diagnose it and prevent future issues.

Whenever you encounter this error, you may want to try refreshing the page and clearing your browser cache. If that doesn’t resolve the issue, you might need to deactivate your plugins, disable your CDN, or contact your host for assistance. 

Alternatively, you could restore a backup of your site. By using a service like Jetpack Backup, you can easily restore previous versions of your content. If the error goes away, then the cause was likely a change made since the time of that backup. You can then use Jetpack’s activity log to track these changes and resolve the issue.

This entry was posted in Learn. Bookmark the permalink.


Simon Keating profile

Simon Keating

Simon has worked in marketing and product development for over 10 years, previously at HubSpot, Workday, and now Automattic (Jetpack). He has a varied education, with a degree in chemical engineering and a masters in computer science to his name. His passion is helping people and their businesses grow.

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site.


Get up to 51% off your first year.

Compare plans

One of the most frustrating aspects of running a website is having to troubleshoot an error when you don’t know why it’s happening. Some issues, such as the 502 bad gateway error, have many potential causes. This means you may need to try multiple solutions before you land on the right one. In this post we’ll show you how to navigate this tricky error and resolve it.

Let’s get to work!

Subscribe To Our Youtube Channel

  • 1
    What the 502 Bad Gateway Error Is (And Why It Happens)

  • 2
    How to Fix the 502 Bad Gateway Error

    • 2.1
      Clear Your Browser Cache

    • 2.2
      Temporarily Disable Your Content Delivery Network (CDN)

    • 2.3
      Test WordPress Themes and Plugins

    • 2.4
      Other Quick (Potential) Fixes

  • 3
    Conclusion

What the 502 Bad Gateway Error Is (And Why It Happens)

The 502 bad gateway error in action.

The 502 bad gateway error pops up from time to time, and often means there’s a problem with your server.

When you visit a website, your browser sends one or more requests to the server that hosts the site. If everything is working properly, that server will send back the information your browser asked for, and the website will load. On the other hand, the 502 bad gateway error occurs when a server sends back an ‘invalid’ response. This can mean that the connection timed out, or can be the result of several other issues.

From the Mozilla Developer Network, the official definition is:

The HyperText Transfer Protocol (HTTP) 502 Bad Gateway server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server.

So far, this may sound simple. However, the connection between your browser and most websites isn’t as straightforward as it used to be. For example, your browser’s request might get routed through a proxy server before making its way to the host in question, so it can be hard to pinpoint where the issue is located. A lot of websites also use multiple servers, which complicates things even further since any of them could be the cause of the 502 error.

All of this means there are a few potential causes for this particular error code. It could be the result of:

  • Errors in your database.
  • A server that is timed out, currently unavailable, or just not working as intended.
  • The server is overloaded with too many requests. Perhaps a DDOS attack, or even just a larger-than-intended spike in traffic.
  • A problem with your reverse proxy server.
  • Faulty PHP scripts, courtesy of one of your plugins or themes.

The good news is that if the problem is server-side, you may not need to take any action. In these cases, your hosting provider will usually jump to the rescue quickly (since clients tend not to appreciate downtime). You should make sure to contact your host’s support team as soon as possible after receiving the notice that your site is affected by a 502 error.

With that in mind, we’re going to focus on what to do if the 502 bad gateway error doesn’t go away on its own quickly. Most websites can’t afford to be down for hours at a time, after all, so if this error persists it’s time to start troubleshooting on your end.

How to Fix the 502 Bad Gateway Error

Before you shift into troubleshooting mode, there’s one quick test you can run to determine if your server is responding as it should. You can try running a traceroute, to see if your server is reachable in the first place. If it is, then the problem is probably on your end. If not, this is when you may want to get in touch with your hosting provider.

You should also try resetting your router, and checking your Domain Name System (DNS) settings. These are basic fixes that can sometimes make the 502 error go away, and they’re easy enough to tackle on your own. If you find that neither solution solves the problem, however, you can use the following methods to troubleshoot the 502 error.

Clear Your Browser Cache

The 502 error can appear when you try to access your website, even if the underlying problem has been resolved. This occurs if your browser is relying on its cache, rather than loading the latest version of your site from the server.

Simply reloading the site a few times can often do the trick. Especially if you’re using the Forced Reload via Shift-CTRL-R on Windows or Shift-CMD-R on Mac.

If all of the above fails, you should proceed to empty your browser’s cache manually. Chrome users can do this by navigating to the Settings > Advanced menu, and locating the Clear Browsing Data option:

Clearing your browser's cache.

Look for the Cached Images and Files option under the Basic tab, and click on Clear Data after selecting it. Keep in mind that this menu will also delete your browsing history, if you don’t disable that setting before clicking on the Clear Data button.

This same process can also be completed using Firefox, Safari, Internet Explorer, and just about any other browser. When you have cleared the cache, try reloading your website once more. If the error persists, it’s time to get serious. For more information on clearing the cache, you can find it over at Hubspot’s hub page on the topic.

Temporarily Disable Your Content Delivery Network (CDN)

Earlier, we mentioned that your browser requests will sometimes be routed through a reverse proxy server. In other words, using a proxy server places an intermediary between the user’s browser and the website’s server.

Some services, such as Content Delivery Networks (CDN), rely on reverse proxy technology to route incoming traffic as efficiently as possible. However, sometimes this extra layer can create issues when you’re trying to connect to a website’s origin server. When that happens, your visitors (and you) might run across the dreaded 502 bad gateway error.

Fortunately, it’s easy enough to check and see if your CDN is causing this issue. All you have to do is temporarily disable the service, and then test whether your website loads correctly without it. The process of disabling your CDN will vary depending on the service you’re using, but it’s usually simple.

For instance, Cloudflare users just have to navigate to the Overview tab in their dashboard. Inside, you’ll find a list of properties that are running the service. Then you’ll need to look for the big Pause button in the Pause Website section, and click on it:

Pausing your CDN service.

Now, when you try to access your website, its origin server will respond to the request without any middlemen getting in the way. If the 502 error is gone, then your CDN was probably the source of the issue. In most cases, you’ll just need to wait a few hours before re-enabling the service. Of course, be sure to check and make sure that the error is still gone afterwards.

If you’re using another CDN, you’ll need to look at its documentation for instructions on how to temporarily disable the service. However, if your CDN turns out not to be the problem, there’s one more fix you can try.

Test WordPress Themes and Plugins

So far, we’ve talked about three potential causes behind the 502 error: your server, your browser, and middleman services such as CDNs. That only leaves one option if you’re sure the problem is on your end, and that is your website. If you are running WordPress specifically, one of your plugins or themes might be trying to execute a script that your server can’t load correctly. This can result in an invalid response when your browser sends a request, triggering the 502 error.

You can only have one active theme at a time, so you can simply deactivate your current one and switch to a default WordPress theme temporarily, to see if that resolves the error. On the other hand, figuring out if a plugin is causing problems can take more time, depending on how many of them are currently active.

Since you don’t have access to your dashboard at the moment thanks to the error, you’ll need to disable your plugins and themes manually. Keep in mind that this process doesn’t involve deleting the plugins and themes, and reactivating them only takes a moment. So your website’s functionality shouldn’t be affected. Even so, you should have a recent backup ready just in case. If you don’t already have a backup solution in place, take a look at this list of the best WordPress backup plugins.

Then, open up the FTP client of your choice. We’re big fans of FileZilla, so we’ll be using that as our example. Log into your website via FTP, and navigate to the public_html – wp-content – plugins folder. There should be a folder for each of your installed plugins inside – even those that aren’t active:

Your WordPress plugin directory.

If you right-click on any of those folders, you’ll see several options, including one labeled Rename. Click on that now, and change the name of the folder to something like disabled.pluginname:

A disabled WordPress plugin.

When you access your website now, WordPress won’t be able to find that plugin, so it will load without it. If the plugin you just deactivated was causing the 502 error, your website should load correctly. Just to be sure, remember to use the CTRL + F5 command (or the OS X equivalent) to force your browser to delete its cache before reloading the site.

To avoid confusion, you should troubleshoot one plugin at a time. Change a folder’s name, try reloading your website, and see if it’s still displaying the 502 error. If it is, restore the folder’s original name. Repeat this process with each folder until you’ve found one that’s causing the error, or until you’ve tested every plugin. You can use the same process to test your active theme, which will force WordPress to use one of its default themes instead.

If one of your plugins or themes is causing the 502 error, you can delete it altogether and look for a replacement. If it’s outdated, you can also try updating it, to see if that resolves the problem. In some cases, the problem script will be patched quickly, so you can always resume using that plugin or theme later on.

Other Quick (Potential) Fixes

Now, these above fixes are likely going to find and fix the culprit if the 502 error is being caused by something on your end and not the server’s. If it doesn’t go away, remember that we suggest you contact your web host to let them sort through the server and diagnose any issues there.

That said, you can help speed up the process by performing a couple of quick checks.

The first of these checks being any logs your site might have saved. If it’s WordPress, there are a number of ways to see it. We have a solid write-up on using these logs to improve your site that may be of some help here. WP sites running versions 5.0 or greater are equipped with a Site Health tool that you can check inside your admin dashboard, so make sure you see what it has to say.

You can also make sure that your browser’s cookies are clear. These are entirely separate from the cache, and we don’t always want to clear these out. If you keep any information saved in your browser, this will wipe it out. But those same cookies may also 502 the connection between you and those sites, so it can be a Catch-22. Either way, it’s pretty easy to clear the cookies in any major browser.

If your site just stalls out, it might be that there’s something in the background that just needs more time to execute. You can increase the execution time allowed by a WordPress site pretty simply by editing your functions.php file. If you’re not on WP, you can do it via .htaccess or php.ini, too. Thimpress has a pretty good guide on how to get this all done.

Finally, you can check for DNS errors. By that, we mean that you’ve moved hosts or changed to a different kind of plan or server itself. You might have adjusted nameservers or any number of things that could go awry. DNS settings are very specific and prone to misconfiguration. So go into your cPanel or dashboard, make sure that everything lines up between your host and your domain registrar and the settings on your website itself. Sometimes a wire gets crossed or a single typo stops everything in its tracks. A little DNS proofreading can go a long way here.

And if you’re really interested in making sure the DNS is okay on your end, you can fire up the terminal and flush your DNS cache manually.

Conclusion

Troubleshooting WordPress errors is often easier than you might think. Even issues that have a lot of potential causes, such as the 502 bad gateway error, are well understood and documented. You might have to try out multiple solutions before you land on one that works, but the troubleshooting process shouldn’t take too long if you follow the right instructions.

If you run into the 502 bad gateway error on your website and it doesn’t go away after a few minutes (or after a quick call to your host’s support team), chances are the problem is on your end. Just go through the processes and tricks we mentioned above, and you and your users should be back on your website in no time.

Have you ever run into the 502 bad gateway error on one of your websites? Share your experiences with us in the comments section below!

Article thumbnail image by windwheel / shutterstock.com.

If you have a WordPress website of your own or are a regular WordPress user, you must be familiar with occasional error messages such as 502 Bad Gateway. Encountering such problems on your site can be quite frustrating and confusing for many reasons, starting from unclear causes to poor SEO rankings. However, you can quickly troubleshoot these bad gateway issues following some simple, easy steps. 

502 Bad Request Error

When your WordPress website shows the 502 Bad Gateway error code, it is quite hard to pinpoint the exact cause of the trouble. It is usually a result of a complex, faulty connection between the user, the server, the web program, and many other external factors surrounding the web. 

Even though it is difficult to understand the reasons behind this connection error, there are some tried and tested solutions to it. You can use a few simple ways to resolve 502 Gateway errors effortlessly without breaking a sweat. But before we dive into the solutions, let’s find out what this error means and some of its possible causes. 

What Is A 502 Bad Gateway Error In WordPress?

A 502 Bad Gateway Error indicates that there is a problem with the website’s server communication. It is an HTTP status code that means that the web servers did not properly process your request for a certain action. 

502 Bad Gateway Error

According to the Internet Engineering Task Force (IETF), a 502 Bad Gateway Error is a status code that indicates the server received an invalid response from an inbound server it accessed while attempting to fulfill the request.

In simpler words, every time you visit a website, your browser sends a request to the webserver. After processing the request, the webserver “returns” the requested data along with an  HTTP status code and HTTP header.  

This is where the 502 (Bad Gateway) error comes in. It indicates that your browser’s web server while acting as a gateway to relay information and data from another server, has received an invalid or faulty response. 

Types Of 502 Bad Gateway Errors

Website designers can customize what a 502 Bad Gateway Error will look like depending on the various web browsers, servers, and operating systems. There may be multiple names and visualizations for it on different websites, but they all point to the same error. 

502 Bad Gateway Error

You might have seen this server communication error named as one of the following:

⚠️ “502 Bad Gateway”

⚠️ “Error 502.”

⚠️ “HTTP Error 502 – Bad Gateway”

⚠️ “502 Service Temporarily Overloaded”

⚠️ “HTTP 502.”

⚠️ Temporary Error (502)

⚠️ 502. That’s an error

⚠️ “502 Server Error: The server encountered a temporary error and could not complete your request.”

Some web pages simply put up the error code while others, like Twitter, show a completely customized heading and image to imply excessive traffic on site

502 Bad Gateway Error

Possible Causes Of  502 Bad Gateway Error 

As mentioned earlier, there isn’t a specific reason behind 502 Bad Gateway Errors. Instead, there are a handful of possibilities that may lead to miscommunication between web servers. 

🎯 A Server Overload

When a website is overcrowded with far more traffic than usual, it reaches its memory capacity and gets overloaded. It can cause server communication issues and occasional server crashes. 

🎯 Network Errors 

Several network errors, including potential DNS changes, routing issues, and ISP-related problems, may trigger 502 Gateway Errors on your WordPress website. 

502 Bad Gateway Error

🎯 Blocked Server Transmission By Firewall

A firewall is used to protect your websites and content from potentially harmful traffic. However, a Firewall may sometimes mistake safe content as malicious and prevent traffic from getting through. 

🎯 Faulty Programming 

The simplest issue that results in 502 Bad Gateway errors on your websites may be faulty programming. If your WordPress website has internal errors with its codes, servers will not be able to connect and display any content. 

🎯 Server Software Timeouts 

If a server takes too long to load, it may result in the caching tool reaching its timeout limit and trigger server gateway errors. 

Ways To Resolve 502 Bad Gateway Errors In WordPress With Few Easy Steps

A 502 Bad Gateway Error is usually a problem that arises from network or server errors. However, it might also be the result of simple connectivity issues on the user end. 

502 Bad Gateway Error

In this blog, we will look at some quick fixes to all your Bad Gateway errors in WordPress that will work perfectly for WordPress owners and WordPress website users.

✅ Refresh And Reload The Web Page 

502 (Bad Gateway) errors usually result from temporary issues in server connectivity. As mentioned earlier, this can be due to a surge in website traffic that overloads the site and the server. In such cases, the easiest solution can be to reload the web page simply. 

When encountering Bad Gateway errors, the first thing you should do is to wait a minute or so and then hit a refresh (or F5 or Ctrl+F5) on your web page. If it isn’t a significant problem with the server or the connectivity, this is sure to get your WordPress website running again. 

✅ Look For Any Server Connectivity Issues

Server maintenance is the process of keeping the server software up to date and running. It is essential to prevent network failures and to ensure your computer network can operate smoothly. 

However, the whole process can be time-consuming and render your website down for the time being. During server maintenance, you and your website visitors can come across 502 Bad Gateway errors that will prevent you from accessing the site. 

At times like this, the only way to troubleshoot this problem is to wait and allow your server to finish maintenance. You can access the site after hitting refresh or trying to enter the site again a short while later. 

✅ Try To Load The Site On A New Browser

Sometimes the browser you use may fail to detect connectivity with web servers and trigger a Bad Gateway error on your WordPress websites. It is challenging to notice such minor issues caused by your browser. 

Hence, if you come across a 502 Bad Gateway Error message on your web page, you must try to load your site on a new or different browser. You can also try opening your website in an incognito window. If the problem arising is browser-related, using a new browser will definitely allow you to connect to your website. 

✅ Clear The Browser Cache And Cookies 

Caches are usually used to create a static version of websites, which reduces the back and forth communication between a web browser and a database server. Caches are meant to improve website speed and site performance. Caching also ensures less load on your hosting servers. 

502 Bad Gateway Error

On the other hand, website cookies or HTTP cookies are small pieces of data stored on a site user’s device to keep track of their activities. Cookies help to serve up targeted information to your users. 

However, when web browsers, such as Chrome and Firefox, store outdated information in their cache and cookies, they can cause server miscommunications that result in bad gateways and 502 errors. 

If your WordPress website shows 502 Bad Gateway errors, you can clear your browser caches and cookies. This will not only help to resolve bad gateway errors but also make your website run faster. 

To learn more about WordPress caches and how to remove them, we recommend you read this blog

✅ Use A VPN To Access Your Website

Various online VPNs facilitate creating an encrypted connection between your browser and a remote server, which tunnels all your website traffic. Since your browser uses an encrypted server link, your network IP address is hidden, masking your identity and location to ensure privacy. 

If 502 bad gateway errors appear on your WordPress website due to server or ISP errors, you can try to reroute your connection using Virtual Private Networks (VPNs). This way, your WordPress website will be connected to a new server, and gateway errors will be resolved immediately. 

✅ Restart All Your Networking Equipments 

Sometimes, it is not your web server that is faulty or causes a bad gateway connection. If you test your server and determine that the 502 Bad Gateway Error persists, it might be due to a bad connection on your network’s part and not a result of faulty server responses. 

This can happen through possible temporary connection errors on your computer or your networking equipment, such as your wifi, router, modem, etc. A simple restart of your computer and your networking devices might be the solution to any bad gateway errors.

✅ Update WordPress Plugins, Themes, And Extensions

It is also important to check your WordPress website plugins, themes, and extensions. Wrong codes due to third-party plugins and themes and issues with misconfigured caching plugins often lead to bad server gateways and 502 errors on your website. 

502 Bad Gateway Error

To make sure your WordPress plugins are not causing server communication errors on your website, you can deactivate and then update your plugins. If this fixes the server error, the problem was with one of your plugins. You can quickly determine which plugin was the faulty one by reactivating them, one at a time

If the issue still does not get resolved, you need to follow similar steps with your WordPress themes and extensions. You can update and re-activate them to troubleshoot any server communication difficulties.  

✅ Temporarily Disable Your CDN And Firewall Connection

If you are using a third-party content delivery network (CDN) or a website firewall, chances are that they are causing bad gateway communication due to faulty configurations. Some providers offer complete proxy services with extra firewalls or DDoS protection.

A defective firewall configuration can cause requests from a content delivery network to be interpreted as an attack on your server and rejected, resulting in a 502 Bad Gateway Error. It’s also possible that your WordPress security plugins will prevent contact between the servers or even block your local or ISP IP address.

To troubleshoot this issue, you will simply have to disable your firewall connection temporarily. Doing so will remove any extra layer of protection between your browser and the hosting server and should get your website connection back on track. You will be able to disable your firewall via your protection provider’s admin console.

However, it can be risky to disable your firewall protection because it can make your device or network vulnerable to unauthorized access from online. So you need to be extra careful if you want to try this method. 

✅ Check For DNS Issues And Change DNS Server

502 Bad Gateway Error

A 502 Bad Gateway Error can also result from a DNS issue. The domain might not respond to the correct IP address, or the DNS server might not be responding. If you’ve recently changed host servers or transferred your website to a different IP address and can make changes to your website’s DNS server. 

Migrating from one DNS server to another involves reconfiguring the server, and this might take up to 48 hours to propagate fully. In this case, you will have to wait for the propagation to complete.

You can also try to flush your DNS cache or change your DNS server if it is not done earlier.  

✅ Restart PHP To Resolve Any PHP Timeout Issues

If you’re importing a large number of WordPress files, you could get an error 502 bad gateway as a result. This happens when a single PHP process runs longer than it should.

You can contact your web host and find out the maximum time set in your PHP configurations and increase it if needed. Restarting PHP can also be helpful. However, if you want to do it correctly, you can contact the WordPress support team.

What To Do If All Attempts Fail And 502 Bad Gateway Error Persists?

If the 502 Bad Gateway errors persist after trying all of the procedures mentioned above, we recommend contacting your web host and asking for help. They will surely know what to do and will be able to inspect their server problem logs or have their own backups of your WordPress site, for example.

Effortlessly Troubleshoot 502 Bad Gateway In WordPress

As you can see, there are multiple ways to troubleshoot 502 Bad Gateway errors in WordPress. Although a server usually causes such issues, there is still something you can do on your end to resolve the issue. We hope that these quick fixes will help you resolve any 502 errors and ensure a smooth browsing experience on WordPress.

502 Bad Gateway Error

If you found this blog helpful, let us know by commenting below; we would love to know! To get more useful tips like these, please subscribe to our blogs and join our friendly Facebook community.

Post Views: 1,173

WordPress errors such as 502 bad getaway error frustrate and annoy the website owners and the users and visitors on your website. This is one of the most usual WordPress errors, and others such as the error establishing the database connection or white screen of death also create a lot of performance and other website issues.

502 bad gateway error is especially popular as it affects smaller websites and huge services such as Twitter, Gmail, CloudFlare experience this issue. This error has several potential causes, and you need to try multiple solutions to help resolve this issue.

In this blog, we will cover the following sections:

  1. What Is the «502 Bad Gateway Error»?

  2. What Causes 502 bad gateway error?

  3. How does the 502 gateway error impacts website’s SEO?

  4. How do I fix and resolve the 502 bad gateway error on my WordPress website?

What Is the «502 Bad Gateway Error»?

The 502 bad gateway server occurs when the website’s server your browser sends a request to receives an invalid request-response.

Gateway is essentially referred to as a device that is used to enable networks communications. Sometimes, your web server acts as a gateway that tries to tell you that it has received an invalid response through this error. Therefore, it is crucial to understand that this issue is a server-level error, not specifically a WordPress or your website’s issue

This invalid response could be the result of connection time-out or other different issues.

What Causes 502 Bad Gateway Error?

Before you troubleshoot this error, it is first important to figure out what is causing it. There could be several different reasons or causes of this error which includes:

  • Browser errors
  • Database errors
  • Outdated software
  • Error due to server overload
  • Plugin incompatibilities
  • Corrupted cookies or caches files
  • Problems with a router or other home networking equipment
  • Reverse proxy server problem
  • An unavailable or timed-out server
  • Faulty PHP scripts

How does the 502 gateway error impacts website’s SEO?

The 502 bad gateway error negatively impacts your website’s SEO (Search Engine Optimization). SEO is important for your website to perform well on the SERP (Search Engine Results Page) and to gain quality traffic.

If your website is down only for a few minutes, let’s say around 10 minutes, the crawler simply delivers the page from cache. And by the time Google re-crawls it again, you resolve the issue, and your website is up and running back again. If this is the situation, you do not have to worry about the SEO impact, and your website is completely fine

On the other hand, if you do not resolve this error right away, and your website is down for a long period for multiple hours, Google sees this error as a site-level issue that is required to be addressed. This significantly affects your rankings, and Google’s crawlers can push your website down to a lower SERP position.

If your website is consistently facing this issue and needs a solution, go through the following list of solutions that can assist you fix this error quickly and efficiently.

How do fix and resolve the 502 bad gateway error on my WordPress website?

This error is caused mainly because of the network/server issue. Or it could also be your client-side issue. Before you reach out to your hosting provider, you must implement the following strategies.

Here are some ways through which you can resolve the 502 bad gateway error and get your website up, running, and accessible to your customers again.

  1. Reload the page or refresh it
  2. Remove all cookies and caches from your web browser
  3. Check for the DNS Issue
  4. Turn off the firewall and CDN temporarily
  5. Verify your themes and plugins
  6. Check Your Logs
  7. Restart WordPress Site
  8. PHP Timeout Issue
  9. Contact your host provider`

1. Reload the page or refresh it

Whenever you encounter the 502 bad gateway error, one of the simplest solutions and the first step to fix this issue is to try reloading your website (F5 or Ctrl + F5).

Your server or host may be simply overloaded. So once you reload or refresh your web page, it can help solve the issue, bringing the site back. Meanwhile, you can also try loading the website on a different browser, such as Mozilla Firefox, Microsoft Edge, or Safari, to check if it works on those browsers.

Reload Your Page

Another simple solution, while you are waiting to load your website, is to paste your website’s URL into downforeveryoneorjustme.com. This solution will ensure if your website is really down or if it is a problem on your side.

2. Remove all cookies and caches from your web browser

Clearing your browser’s cache can also sometimes help errors like this and instantly fix them. This solution varies from browser to browser and depends on which browser you are using.

On Google, you can clear your browser’s cache by clicking on the three-dot icon on the right-side corner of your window. Click on Settings, and then on Privacy and Security. Click on the first prompted option, which is Clear browsing data, which will open a pop-up window.

Make sure to check the check boxes beside Cached Image & files, Cookies and other site data. And then click on the Clear data tab.

Once you complete this process, close the settings page, and reload your website’s page. If the error was because of the cookies and caches, the error should be gone now, and your website should run smoothly and efficiently.

3. Check for the DNS Issue

The 502 error could also be caused by the DNS issues, such as the DNS server not responding or the domain not getting resolved to the correct IP.

If you have just recently migrated your WordPress website to a new host, it is crucial to wait for a while until things fully propagate. Sometimes, you will also have to wait for over 24 hours, as it depends upon the Time To Live (TTL) value of your DNS (Domain Name Server) records.

Or you can also try flushing your local DNS cache, which is similar to clearing your browser’s cache.

You can implement this solution by entering the following code:

i.) From your Windows machine’s command prompt:

ipconfig/flushdns

If it runs successfully, you shall see the “Successfully flushed the DNS resolver Cache” message.

ii.) For MAC OS users, you must enter the following code in the terminal:

dscacheutil -flushcache

You won’t see a success message here on macOS as you see on Windows.

You could also try temporarily changing your DNS servers to a public DNS server.

4. Turn off the firewall and CDN temporarily

The 502 bad gateway error could also be because of an issue with your firewall of a CDN (Content Delivery Network). It is wise and preferable to temporarily disable your CDN if you use a third-party CDN provider to troubleshoot this error easily.

For example, if you use WordPress’s CDN enabler plugin, you can just deactivate the plugin and then test your website. The same goes with any other CDN plugin that you have hooked your CDN with, such as WP Rocket.

This issue can also occur with providers such as CloudFlare that provide fully proxy services or DDoS protection, as they have some extra firewalls in between. It is important to reach out to those providers and fix the error issue.

CloudFlare Bad Gateway Error In Host

5. Verify your themes and plugins

Many a time, a bad code on your WordPress website from a third-party theme or plugin could be the reasons behind your queries and scripts being cancelled. Also, a lot of misconfigured caching plugins lead to the 502 eros generation.

You can resolve this issue by deactivating all your caching plugins. Do not worry about loss of data when you deactivate a plugin, as your data remains the same.

You can also reach out to and contact the plugin developer for support and help. Or you can go to the WordPress Repository and post a support ticket.

It is crucial to ensure that your themes and plugins are up to date. You might also need to contact and get help from the WordPress Developer to fix the issue if there is bad code in a plugin.

6. Check Logs

You must also take advantage and check your error logs to fix the 502 bad gateway issue. Your host provider must provide you with this option.

Atatus Log Monitoring

You can also monitor you logs for performance bottlenecks using Atatus Log Monitoring which provides intelligent insights about your Log events.

7. Restart WordPress Site

This is another option that you can try, restarting WordPress site, which quickly helps resolve the issue. If your hosting provider does not provide this option, you can open and raise a support ticket and request them to restart the PHP.

8. PHP Timeout Issue

PHP timeout issues are a common occurrence if you are implementing big WordPress Imports. A 502 error is generally displayed when this occurs.

You must contact your current WordPress host about the values set on your servers and ask them to increase those values if possible. The values also depend on your type of current hosting plan.

9. Contact your host provider

If none of the above-mentioned steps or solutions works for you, you must get in touch with your web host provider. Usually, these errors, such as the 502 error, occur because of an issue from the hosting provider. Sometimes a request, query, or script will take longer than usual, killing or cancelling the server. Most hosts, especially the shared hosts, implement a “kill script” that creates a bad gateway.

Another reason could be that your web host’s server is not reachable or is unavailable because of no connectivity or server downtimes. You must reach out to your web host in such situations, or you can also raise a support ticket or check your WordPress host’s status page.

Conclusion

Any error that takes your website down or makes it inaccessible to your users and customers is a serious threat to your WordPress website. It can negatively affect your businesses sales and search engine visibility.

There are several solutions to troubleshoot this issue and fix the 502 bad gateway error. Whether the problem is with your host or with your client-side, I hope the solutions mentioned above help you fix the issue and get your website up and running again.


Atatus: Complete Visibility Into Your WordPress Site

Do you want to know the performance bottlenecks in your WordPress Site?

You can monitor your WordPress site with Atatus and get in-depth insights about the performance and availability on how your site is performing. We also offer tools to monitor Application Performance, your entire Infrastructure and Logs.

Start Monitoring Your WordPress Site!!!

Понравилась статья? Поделить с друзьями:
  • Ошибка 502 сбой сервера
  • Ошибка 502 bad gateway joomla
  • Ошибка 502 сбербанк
  • Ошибка 502 adobe
  • Ошибка 502 при включении ноутбука hp