Любая ошибка, из-за которой ваш сайт 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.
После этого перейдите к wp-content и найдите папку с плагинами . Переименуйте папку во что-то вроде plugins.old, чтобы отключить сразу все ваши плагины. Не волнуйтесь, вы не потеряете никаких данных.
Обновите свой сайт, чтобы увидеть, исчезла ли ошибка. Если вы видите свой сайт вместо ошибки, проблема в одном из ваших плагинов.
Переименуйте plugins.old обратно в плагины и войдите в панель администратора WordPress. Пора найти проблемный плагин.
Активируйте плагины один за другим, перезагружая свой сайт после каждой активации. Повторяйте это, пока не определите плагин, вызывающий проблемы. Проблемный плагин, очевидно, воссоздает ошибку 502 неверного шлюза при активации, которая может заблокировать вас из области администратора.
Полностью отключите или удалите плагин через FTP или файловый менеджер, получите альтернативу или обратитесь к разработчику за дополнительной поддержкой.
7 Устранение неполадок активной темы
Если ваши проблемы начались после обновления вашего сайта, то есть тем, плагинов и WordPress, а деактивация плагинов ничего не исправляет, вам необходимо устранить неполадки в вашей теме WordPress.
Проверка, является ли ваша тема проблемой, немного отличается от плагинов для устранения неполадок. Давай покончим с этим.
Войдите в корневой каталог WordPress через FTP или файловый менеджер. Затем перейдите к wp-content> themes и найдите свою активную тему.
Переименуйте папку активной темы во что-то вроде total.old. Это отключит активную тему и активирует тему WordPress по умолчанию.
Перезагрузите сайт, чтобы проверить, исчезла ли ошибка. Ошибка все еще существует? Это означает, что с вашей темой все в порядке, и в этом случае вам следует переименовать папку с темой обратно в ее исходное имя.
Если ошибка исчезнет, обратитесь к разработчику вашей темы за дополнительной помощью или приобретите профессиональную тему, такую как наша собственная Total.
8 Если проблема не исчезнет, обратитесь к хозяину.
По-прежнему не можете исправить ошибку 502 плохого шлюза на вашем сайте WordPress даже после попытки всех вышеперечисленных решений?
Возможно, проблема на стороне сервера, поэтому просто свяжитесь со своим хостом и получите профессиональную помощь. При этом подумайте о приобретении хоста верхнего уровня, чтобы избежать этой ошибки из-за меньшего количества ресурсов сервера, доступных в планах общего хостинга.
Заключение
Хотя это немного сбивает с толку и разочаровывает, исправить ошибку 502 плохого шлюза легко с помощью решений, которые мы описываем в этом посте. Мы надеемся, что наш пост указал вам правильное направление в этом отношении.
Есть ли у вас какие-либо мысли, вопросы или дополнительные исправления? Помогите нам расширить этот пост, поделившись своими советами, запросами и идеями в разделе комментариев ниже.
Источник записи: https://www.wpexplorer.com
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.”
Twitter displays 502 Bad Gateway Error in a friendlier way.
Google displays a 502 Bad Gateway Error with the suggestion of trying again after some time.
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.
- 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
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.
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.
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.
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).
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.
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.
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.
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.
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
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.
The 502 bad gateway error is one of the most common and most annoying errors you’ll see while online. It happens in WordPress, it happens when browsing random websites, when checking webmail and can literally happen anywhere on the internet.
The 502 bad gateway error is an HTTP error. That usually means something has interrupted the normal process between the web server and your browser. Exactly what interrupted it remains to be seen.
As you’ll see in a minute, there are a multitude of causes of 502 errors and it’s usually a process of elimination to identify that cause.
While this article is concerned with 502 bad gateway errors on a WordPress website, we won’t actually know if it’s the website or not until we have done a few checks.
Therefore, we’ll cover all the relevant troubleshooting steps you can take to identify whether it’s your website or something else.
We’ll also provide fixes for the vast majority of the causes of 502 errors as part of the process.
Table Of Contents
- What Is a 502 Bad Gateway Error?
- What Effect Does the 502 Bad Gateway Error Have?
- How to Fix the 502 Bad Gateway Error
- 1. Reload the Web Page
- 2. Clear Your Browser Cache
- 3. Check IsItDown
- 4. Check Device DNS Settings
- 5. Disable Your WordPress CDN
- 6. Disable Your WordPress Firewall
- 7. Test Your WordPress Plugins
- 8. Test Your WordPress Theme
- 9. Check Your Server Logs
- 10. Increase the PHP Timeout Limit
- Can You Prevent 502 Bad Gateway Errors?
- 502 Bad Gateway Errors
What Is a 502 Bad Gateway Error?
A 502 bad gateway error means a proxy server somewhere between your browser and the website or application you’re trying to contact received an invalid response from further up the chain.
When you type a URL into your browser, the browser will query DNS and be pointed towards the web host that hosts that website.
That host will use a proxy or load balancer to manage traffic. It will receive the query from your browser and send its own query to the web server hosting the website.
If the response it receives from the hosting server is all good, the page loads.
If the response is corrupted, fragmented or not understandable by the proxy, you’ll see the 502 bad gateway error.
HTTP errors are interpreted by the browser you’re using or the service you’re accessing so you might see variations of the error.
Those variations include:
- HTTP Error 502 Bad Gateway
- HTTP 502
- 502 Service Temporarily Overloaded
- Temporary Error (502)
- 502 Server Error: The server encountered a temporary error and could not complete your request
- 502 Bad Gateway Nginx
- 502 bad gateway Cloudflare
They all mean the same thing but reference the service you’re accessing or the CDN the website is using.
Bad Gateway
The vast majority of 502 bad gateway errors you’ll see are network errors and will have nothing to do with you as a user.
There are local causes, such as browser issues, your router or local network and we’ll show you how to troubleshoot those in a little while.
If you’re a website owner and you are seeing this error from your own site, that’s a different story altogether!
We will show you some checks you can make on your website to make sure it isn’t your WordPress configuration, theme or plugin causing the error.
What Causes the 502 Bad Gateway Error?
There are a few situations that can cause a 502 bad gateway error.
- Some errors are caused locally by your browser or local network
- Some can be caused by a CDN, Content Delivery Network
- Others can be caused by the web server itself
- Issues with WordPress such as plugins and themes can also cause 502 bad gateway errors
We will show you how to identify likely causes of 502 bad gateway errors and how to fix them in a minute.
What Effect Does the 502 Bad Gateway Error Have?
The effect of 502 bad gateway errors depends on the situation.
If you’re a user trying to access a website, seeing a 502 bad gateway error is an inconvenience you can avoid by visiting another site.
If you’re a WordPress website owner and are seeing 502 bad gateway errors on your own site, things are a little more serious.
Your visitors may also be seeing 502 bad gateway errors and not be able to reach your site.
Google may choose that moment to crawl your website and will also see the 502 bad gateway error. That will have a negative impact on your SEO until you get the site back up and running.
How to Fix the 502 Bad Gateway Error
There are a range of fixes for the 502 bad gateway error. Some of these will be relevant to general web users as well as WordPress website owners.
Here is a quick breakdown of how to fix the “502 Bad Gateway Error”
- Reload the Web Page
- Clear Your Browser Cache
- Check IsItDown
- Check Device DNS Settings
- Disable Your WordPress CDN
- Disable Your WordPress Firewall
- Test Your WordPress Plugins
- Test Your WordPress Theme
- Check Your Server Logs
- Increase the PHP Timeout Limit
Let’s tackle the fixes in order of complexity with the easiest first. That way, we can minimize the work we need to do to get things working again.
1. Reload the Web Page
Reloading the web page is a useful first step as it takes just a second. We want to force a reload to make the browser request a new copy of the page rather than use its cached version.
For a forced browser refresh use one of these combinations:
- Chrome on Windows: Ctrl + F5
- Chrome on Mac: Command + Shift + R
- Firefox on Windows: Ctrl + F5
- Firefox on Mac: Command + Shift + R
- Safari: Command + Option + R
- Microsoft Edge: Ctrl + F5
2. Clear Your Browser Cache
Clearing your browser cache deletes all saved files, including cached copies of web pages saved for efficiency.
A browser will save a copy of a recently visited page and will show it if you visit the same page multiple times. The intent is to save time and deliver the page quickly but it can get in the way when troubleshooting.
Use one of the following combinations or menu options to access the cache page in your browser:
- Chrome on Windows: Ctrl + Shift + Delete
- Chrome on Mac: Command + Shift + Delete
- Firefox on Windows: Ctrl + Shift + Delete
- Firefox on Mac: Command + Shift + Delete
- Safari: Settings > Safari > Clear History and Website Data
- Microsoft Edge: Command + Shift + Delete
Once you have the data window open, select the option to delete browsing data and cached data. Then retest the website you’re trying to access.
3. Check IsItDown
Is It Down Right Now is one of the most useful websites on the internet. It’s a web-based tool that can check any website or web service to see if it’s working or not.
It’s useful as it can tell you whether the website you’re trying to access is up and it’s just you that cannot reach it or whether the site itself is down and nobody can reach it.
It’s a very reliable way to figure out whether the 502 bad gateway error is a error or part of a larger network or internet issue.
4. Check Device DNS Settings
DNS issues can cause you to see 502 bad gateway errors so that’s what we’ll check next.
You can flush your device’s DNS cache or change your DNS server. Both can, in theory, fix a 502 error.
To flush your DNS:
- Open a terminal in Windows or Mac
- Type ‘ipconfig /flushdns’ and hit Enter in Windows
- Type ‘dscacheutil -flushcache’ and hit Enter on Mac
- Retry the website before going further
You’ll see a success message in Windows but Mac won’t tell you anything.
If you’re still seeing 502 errors, you could try changing your DNS settings. You can do that on your device or on your router.
In Windows:
- Type ‘ethernet’ into the Windows search box and select Ethernet properties
- Select Change Adapter Options in the window that appears
- Right click your Ethernet adapter in the next screen and select Properties
- Select Internet Protocol Version 4 (TCP/IPv4) in the center pane and select the Properties button underneath
- Select the ‘Use the following DNS server address’ option
- Enter 8.8.8.8 and 8.8.4.4 for Google DNS or 208.67.222.222 and 208.67.220.220 for OpenDNS
- Select OK
On Mac:
- Select System Preferences and Network
- Select Advanced and the DNS tab
- Select the ‘+’ icon to add a DNS server
- Enter 8.8.8.8 and 8.8.4.4 for Google DNS or 208.67.222.222 and 208.67.220.220 for OpenDNS
- Select OK and then Apply
If you have DNS set on your router rather than your device, you’ll need to log into the router and change it there.
If you landed on this blog post because you’re seeing 502 errors and don’t own a website, you’re at the limit of what you can do.
Our suggestion now would be to leave the website or service you’re trying to use for a while and try again another day.
If you’re a WordPress website owner and are troubleshooting 502 errors on your own website, your work is not done.
5. Disable Your WordPress CDN
If you use a CDN, Content Delivery Network, on your WordPress website, you could try disabling that. As the proxy server your browser talks to will then need to talk to the CDN server, it could be that server giving the 502 bad gateway error.
If you use Cloudflare and are seeing the custom 502 bad gateway Cloudflare page in your browser, you have two options.
If you see the screen in the image above, the fault is likely at your web host.
If you see the blank white screen with ‘502 Bad Gateway cloudfare’ the fault is likely at Cloudflare. You can check on the Cloudflare service status page.
If you use another CDN, temporarily disable it through your web host’s control panel and retest the site.
If it works, the CDN is at fault so you would need to troubleshoot further with your host or CDN provider.
If the 502 error is still apparent, you’ll need to continue troubleshooting.
6. Disable Your WordPress Firewall
If you use a firewall or security plugin, and you should, now is a good time to troubleshoot that. Firewall configuration issues can cause 502 bad gateway errors and disabling the firewall is a simple test to find out.
- Log into WordPress as normal
- Select your security plugin and the firewall option
- Disable the firewall
- Open your website in another browser tab and retest
If the page loads as usual, it is likely your firewall configuration blocking traffic and causing error 502.
If the error is still apparent, enable your firewall again to protect your website and continue down this list.
7. Test Your WordPress Plugins
Have you added any new WordPress plugins lately? Have any of them updated to a new version? Either situation could cause 502 errors, so let’s tackle those next.
To save time, let’s disable all plugins to begin with.
- Navigate to Plugins and Installed Plugins
- Check the box at the top next to the word Plugin.
- Select the Bulk Actions menu and select Deactivate
- Select the Apply button next to it
Retest your website. If it works now, it’s a plugin at fault. Enable one plugin at a time and retest your site. As soon as you see 502 errors again, disable the last plugin you enabled. If your site works, it’s that plugin causing all your problems.
If the error still appears, it’s not a plugin. Feel free to enable them all again and move on to the next fix.
Here’s how to disable plugins even without accessing wp-admin.
8. Test Your WordPress Theme
A well-coded WordPress theme should never cause error 502 but sometimes bad scripts can cause the server to not respond as expected.
Bad scripts could mean poorly coded or nefarious scripts like those you find in nulled themes. This is one reason everyone recommends never using nulled themes!
To check, let’s enable the default Twenty Twenty-One theme in WordPress.
- Select Appearance and Themes in your WordPress dashboard
- Hover over Twenty Twenty-One and select Activate
- Wait until the new theme has activated and retest in your browser
If the 502 error remains, you can switch back to your main theme.
If the error goes away, it’s your theme and you’ll need to follow up with the developer or use a better theme like Astra!
9. Check Your Server Logs
If it isn’t your CDN, WordPress plugins or themes, it may be an issue with the web server or one of the services you have running on it.
To find out, we’ll need to access your server logs.
If your host uses cPanel, accessing server logs is easy.
- Log into cPanel
- Navigate to Metrics and select Errors
If the server picked up errors, they should appear in the window.
Work through any errors you see to try to identify what’s causing 502 errors. It may take a while but you should be able to identify the cause from there!
Web hosts that don’t use cPanel will have their own log tools. Explore your control panel to find it.
10. Increase the PHP Timeout Limit
We’re not huge fans of increasing the PHP time limit in WordPress. While it can fix numerous errors, including 502, it’s a workaround not an actual fix.
The real fix would be to identify the PHP script that’s taking so long and fix that, but it isn’t always possible. As increasing the PHP timeout limit is possible, it’s all we can do.
To increase the time limit, you’ll need to modify your php.ini file. This controls various elements within WordPress that interact with PHP.
Here’s how to do it.
You’ll find php.ini in your website root in root directory of your web host under public_html.
- Log into your web host and load cPanel or whatever control panel your host uses
- Navigate to your root folder public_html
- Right click php.ini and select Copy
- Name the new file php.ini.bk
- Select the original file and add the following code to the end then select Save
max_execution_time 300
This tells PHP to allow 300 seconds for a script to complete before it errors or terminates the script. While unlikely to cause a 502 error, it has been known, so is a viable troubleshooting method.
If you got this far and will haven’t fixed error 502, we recommend engaging with your web host’s customer support.
Explain what’s going on and explain the steps you have taken and work with them to troubleshoot from there. A good web host will do everything they can to get your site back online again so you should be in safe hands.
Can You Prevent 502 Bad Gateway Errors?
You cannot effectively prevent 502 bad gateway errors as many of the causes are out of your control.
As a web user, the vast majority of times you see the error it will be caused by far end network issues. As long as you work through your local checks, that’s all you can do.
As a WordPress website owner or administrator, you have a few more checks to make but again, the majority of times you see this will be a far end network issue or a server issue.
502 Bad Gateway Errors
That’s everything we know about 502 bad gateway errors and how to identify and fix them.
The majority of times you see the error, it won’t be you at fault, but those times when it is, you now have all the information you need to identify and fix it.
Just work your way methodically through this series of fixes and retest between each. If it’s anything to do with your own device or network, you’ll soon find out.
As a WordPress website owner, you have more work to do but even then, it’s very straightforward to check to see if it’s your website at fault.
After that it’s time to talk to your web host!
Recommended Articles:
- How to fix err_connection_refused error
Do you have any other reliable fixes for 502 errors? See something we missed? Have anything to add? Share your thoughts in the comments below!
Join 1,587,020 Subscribers
Get exclusive access to new tips, articles, guides, updates, and more.
Disclosure: This blog may contain affiliate links. If you make a purchase through one of these links, we may receive a small commission. Read disclosure. Rest assured that we only recommend products that we have personally used and believe will add value to our readers. Thanks for your support!
Ошибка 502 Bad Gateway не зависит от локальных настроек вашего сайта и может обнаружиться на любом устройстве, в любом браузере и операционной системе. Причины появления этой ошибки нелегко идентифицируются и исправляются, в основном, со стороны сервера.
Ошибка 502 генерируется сервером и сигнализирует, что запрос для страницы, сценария или процесса занял слишком много времени для завершения и был принудительно отменен. Главная причина ошибки 502 заключается в нехватке ресурсов на сервере – у PHP-движка закончилась память. Для сайтов на WordPress ошибка появляется при обновлении движка и плагинов или при сохранении больших записей. Это может происходить из-за следующих проблем:
- Очень большой код – много установленных плагинов или очень сложных модулей;
- Чересчур много посетителей на сайте;
- Малое время выполнения скриптов.
Сервера обычно справляются с большим использованием памяти при сотнях одновременных посещений сайта, но в исключительных случаях одновременная загрузка большого количества может вызвать ошибку 502.
Как устранить ошибку WordPress 502 bad gateway
Поскольку ошибка 502 Bad Gateway напрямую связана с серверной проблемой, попробуйте выполнить следующие шаги для разрешения ситуации.
- Повторите заход на сайт. Используйте кнопку обновления в браузере или нажмите F5, чтобы перезагрузить страницу. Повторная загрузка сайта часто проходит без ошибок.
- Вернитесь к сайту позже. Ошибка 502 Bad Gateway может оказаться временной на ресурсе, к которому вы обращаетесь.
- Попробуйте почистить кэш браузера. Поврежденные или устаревшие файлы, которые сохраняются браузером, могут провоцировать эту проблему.
- Свяжитесь с вашим хостинг-провайдером, чтобы прояснить ситуацию.
Если компьютер и сеть работают нормально, а интернет-ресурс показывает ошибку 502, это может быть из-за проблемы с хостингом. Уточните у техподдержки допустимое количество оперативной памяти на вашем тарифе хостинга, при необходимости может потребоваться его увеличить. Попросите также увеличить время выполнения скриптов. В случае регулярных ошибок стоит сменить хостинг-провайдера.
WordPress потребляет большое количество ресурсов сервера, особенно если вы используете множество плагинов. Чтобы проверить, вписываетесь ли вы в установленный тариф, в админке зайдите в меню «Внешний вид — Редактор», из списка шаблонов выберите шаблон подвала (файл footer.php) и добавьте туда строку кода:
<?php include('adplus-right-bottom.html'); ?>
В результате на странице будет выведено количество запросов, время на их обработку и размер затраченной памяти. Если эти числа достигают ограничений, предусмотренных хостером, следует задуматься об оптимизации кода на сайте или расширении объема оперативной памяти на сервере, если это возможно.
iPipe – надёжный хостинг-провайдер с опытом работы более 15 лет.
Мы предлагаем:
- Виртуальные серверы с NVMe SSD дисками от 299 руб/мес
- Безлимитный хостинг на SSD дисках от 142 руб/мес
- Выделенные серверы в наличии и под заказ
- Регистрацию доменов в более 350 зонах
In WordPress, there are many types of error occurs which create confusions and sometimes frustration as well. Error is very helpful in order to determine what is going wrong on our website. If we talk about error the most popular one is 502 bad gateway error.
It is the most popular error because it occurs regularly around the entire web. Here in this blog, we will try to explain What is 502 bad gateway error, its cause and how to fix it?
You always try to visit your website without facing any errors. But some errors like 502 bad gateway error, Page not found 404 error, 500 internal server down stops you to reach your website.
502 bad gateway error occurs not only to WordPress sites, this error is also occurs even in popular services such as Gmail, Twitter, and Cloudflare. So to fix this problem, initially we need to understand the reason for the occurrence of 502 bad gateway error and on the basis of reason try to fix the issue.
WordPress 502 Bad Gateway Error: What it Means?
Basically, a 502 bad gateway error occurs when your WordPress hosting server gets an invalid response for the requested page. But if we talk about bad gateway error there are many types of 500 status error codes (501,502,503,504 ) and all of them have a slightly different meaning.
There are many free web hosting available in the sector you are working on. But almost each of the free websites hosts has some sort of catch out on all the WordPress hosting.
The error basically occurs when you visit a website your browser sends a request to a web server. The web server processes the request received from the browser and then sends back the requested resource along with an HTTP header. HTTP status code is not visible unless something goes wrong.
Web server is a software which receives your request for accessing a web page. It runs only a couple of security checks on your HTTP request and takes you to the web page.
Variations of 502 bad gateway error
Due to various web servers, browsers and operating system there are variations in 502 bad gateway error but there is no difference between them. If we talk about variations of 502 bad gateway error, it is of many types i.e:
- 502 bad gateway
- HTTP Error 502- bad gateway
- Error 502
- 502 Proxy Error
- 502 Server Error
- A blank white screen
- 502 service Temporarily Overloaded
- Temporary error 502
- HTTP 502
- 502. That’s is an error
- Bad gateway: The proxy server received an invalid response from server.
Some of other variations of 502 server error
In this 502 bad gateway error web server received an invalid response while acting as a proxy server. Basically this is your problem with the page you wants to open and it cannot be displayed. In this type of error when the web server contacted the upstream content server then it won’t get any response from the upstream content server.
If we talk about Twitter might shows a different message for a 502 bad gateway error, such as twitter is over capacity and Google display 502. That is an error. The server encountered a temporary error and could not complete your request.
502 error has a negative impact on SEO
If we talk about 502 errors, basically used for WordPress maintenance mode and allows Google to check back at a later time. If we don’t fix the 502 error then 502 error can have a negative impact on SEO because if the site is not working for an extended period of time, say more than 6 hours then Google might see the 502 error as a site level issue that needs to be addressed. This could impact your site rankings.
Here SEO is known as Search Engine Optimization, where search engine is a service which allows all internet user to search for any content, query, and product throughout the world wide web. The search engine optimization of a website needs different tools and strategies. As most of the site is created by using WordPress.
Nowadays web application including a WordPress website is hosted on multiple servers. A couple of servers are enlisted below:
- A web server that serves your website files.
- A database server that runs your WordPress databases.
- The website server that runs the login, PHP code and any other content your WordPress site depends on.
- A gateway server (also known as a reversed proxy server) running software such as Nginx (read as Engine-X),
- Apache and Varnish among others.
When you visit your WordPress website through any browser. It generates multiple requests for all the parts which combine and create the page you see in a browser.
These requests are transferred to the gateway server which finds out where to send the request. Then, the gateway server retrieves:
- MySQL databases from the database server.
- PHP and the other content from the application server.
- Images, JavaScript, CSS, themes, plugins and other files from the web server.
As, CSS stands for Cascading Style Sheet. These are the documents which contain the styling rules that can be applied to HTML or XML, (along with some structural formats).
Causes of 502 Bad Gateway Error
The most common reason for getting 502 bad gateway error is poor communication between your servers. However, this error can occur due to a number of reasons such as:
- Browser cache is acting up.
- Your website server is overloaded.
- You have the Domain Name System (DNS) issues.
- Your Content Delivery Network (CDN) is acting up.
- Problems with your router or networking equipment.
- The speed of Upstream servers is down or can’t be accessed.
- The PHP scripts are full of bugs such as faulty WordPress plugins or themes.
Now let’s move on to fix these errors and make your website error free.
How To Fix WordPress 502 Bad Gateway Error
You never get a clear reason of 502 bad gateway error that’s why to remove this we go through every possible cause of an error and try to fix it:
Reload your WordPress Website
Sometimes your server takes time to respond due to a lower speed and heavy traffic. That’s why you encounter the 502 error. So, Before you try any other method wait for few minutes and reload your website. You can use tools to verify whether your site is down for everyone or for you only.
If the website is down for you only, then the problem is in your end. In this case, you can check your website in a different browser. If the website is down for everyone then you need to proceed further to fix the 502 bad gateway error in WordPress.
Clear Browser Cache
You frequently open your WordPress website in your favorite browser and all of sudden the site start showing 502 bad gateway errors. The simple reason for this is cache saved in your browser.
The modern browser saves the files from your website you frequently open in your browser. Next time when you visit your cache website then the browser doesn’t need to request the same files again and again from the server. Unless you updated the page.
A vigorous caching browser can show 502 bad gateway error. And this problem can be solved by simply clear the cache from your browser and again search for a WordPress site.
Restart Your Networking Equipment
If the changing of browser and clearing cache from a browser is not working for you then move on to next method.
Check out whether your networking equipment is working properly or not.
Malfunctioning of Networking equipment can leads to network error 502 bad gateway. Most of the home network have gateway they do especially when your setup involves a router. This can be a source error 502 bad gateway.
To fix this issue Simply, unplug your networking equipment for 60 seconds and plug it again. If you have a router with modem hybrid, plug in the modem first and wait for 60 seconds then plug in the router.
Switch on the equipment and wait for 2 minutes. Now check is it still showing the error or not? Also, restart your device computer or whatever is showing an error.
Disable Your CDN Momentarily
CDN (Content delivery network) is a service that transfers files on behalf of your WordPress website and boosts the performance of your website.
It is a system of distributed servers around the world that are able to provide fast delivery of Internet content according to the geographic locations of the users. Example of CDN is CloudFlare but, its free plan causes 502 bad gateway error.
We can check whether the CDN is the reason for a bad gateway error. Simply disable the service temporarily and check the error is still appear or not.
If the error 502 bad gateway is due to CDN then contact the service provider for support.
DNS (Domain name system) Problems
A central part of the internet provides a way to match a domain name to IP addresses. If your domain does not reach to a right IP address then you encounter with a 502 gateway error. As a matter of fact, when you migrate your domain to a new host this involves the change in DNS name server.
Does the complete migration task take between 12 to 36 hours which could result in a bad gateway error? Best is to allow the domain to migrate completely and successfully.
Other then this we can clear the local DNS cache and change DNS on router & devices to avoid bad gateway 502 error.
Fix Error of Your WordPress Plugins & Themes
Poorly coded plugins and theme instigate the scripts and queries that confuse your server. The server is not able to recognize and it cancel the order. That’s why you receive a bad gateway error 502.
Here, A plugin is defined as a type of software that contains a group of functions that can be added to a WordPress website. They are used to provide additional functionality to your application and theme is a group of stylesheets and templates that are used to describe the appearance and display of a WordPress site.
The poor coding is not always the reason for gateway error. Besides this plugin using third-party services like reCaptcha also cause the error. Sometimes, NGINX rejects the long tokens generated by Google when showing reCaptcha.
By adding reCaptcha you increase a difficulty for random commenters. The reCaptcha is clear by a human only. So you can easily avoid the comments generated by robotic machines.
How to find out problematic plugin
If you think your plugin is creating the issue you can fix this. Access your WordPress root directory and move to the wp-content ➤plugin, and rename the plugin folder. This will deactivate your plugin for a while.
Reload your site and check the error is disappear or not. If the error is disappeared then rename the file same as the previous name.
Reactivate your plugin and check whether the error appears or not.
Doing this for all plugin will help you to find out the problematic plugin. You can replace the problematic plugin with other plugin or ask for developer support.
How to find out problematic theme
If the plugins are not creating the problem then maybe the theme is creating the issue. To find out whether the theme is the reason for bad gateway error access your WordPress root directory via FTP. Here, FTP stands for File Transfer Protocol. It is a “means of transport” i.e it is used to transfer files from one local computer to a remote website
Move to wp-content ➤theme➤ Your active theme.
Download a copy to your computer as a backup. Now, Click on your active theme and delete it from your WordPress root Directory.
Reload your Site if you saw a white screen instead of an error, then there is the problem. Activate your default theme meanwhile fix the problematic theme.
Update WordPress core, theme & plugin
An outdated version of WordPress, Theme & plugin conducts errors as well as the security risk. Regular updates can fix the errors and save you from disasters of security.
So, Keep you WordPress, theme & plugin updated to avoid such errors.
Check your hosting server
If all the discussed solution is not working for you then it might be an issue with your hosting server. You need to contact your host server Support team and explain the problem you are facing.
Mention all the troubleshooting steps you have taken to fix the issue. All WordPress hosting companies will be able to quickly fix the issue if it is caused by the server.
Check Logs
We can also take advantage of the error log file. Basically, an error log is a record of critical errors that are encountered by the application, operating system or server while executing the code. So with the help of an error log, we can quickly handle the issue.
We can also check the log files in Apache and NGINX which are generally located:
- Apache:/var/log/apache2/error.log
- NGINX:/var/log/nginx/error.log
Php timeout issue
Basically, Php timeout occurs if a single PHP process runs more then the max_execution_time or max_input_time set in the PHP configuration on your server.
This basically happens when you’re doing big WordPress Imports and when all of these processes occur then a 502 server error is usually visible and the maximum PHP timeout values available on any platform is based on the current plan.
Check Scripts
Since we create custom themes and functionality in WordPress and sometimes this custom function is also the reason for not handling the HTTP request by the server. Because it generates long tokens which can put stress on the server and because of that 502 bad gateway error occurs.
That’s All!
Conclusion
As you can all of the possible ways to fix a 502 gateway error on your WordPress site. Basically, it is not a client-side based problem but rather than issues with your host. Be aware of third-party plugins and themes with bad code and sometimes the queries which are not optimized are also created a problem.
Hope this beginner guide is help for you. In case of any related problem, use the comment box provided below. Also, share the blogs with your peers.
Still if you are facing any problem, then you can contact to our WordPress support developers by dialling our WordPress help number +1-855-945-3219 (Tollfree).