Ошибка 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.

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.

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

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.

Ошибка 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 зонах

How to Fix the 502 Bad Gateway Error in WordPress

Updated on March 15, 2023 Simon Keating

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 66% off your first year.

Compare plans

Have a question?

Comments are closed for this article, but we’re still here to help! Visit the support forum and we’ll be happy to answer any questions.

View support forum

Понравилась статья? Поделить с друзьями:
  • Ошибка 502 bad gateway ubuntu
  • Ошибка 502 bad gateway nginx как исправить
  • Ошибка 502 bad gateway joomla
  • Ошибка 5011 canon как исправить
  • Ошибка 502 504 что это