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
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.
Любая ошибка, из-за которой ваш сайт 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
One of the most frustrating aspects of running a website is having to troubleshoot an error when you don’t know why it’s happening. Some issues, such as the 502 bad gateway error, have many potential causes. This means you may need to try multiple solutions before you land on the right one. In this post we’ll show you how to navigate this tricky error and resolve it.
Let’s get to work!
Subscribe To Our Youtube Channel
-
1
What the 502 Bad Gateway Error Is (And Why It Happens) -
2
How to Fix the 502 Bad Gateway Error -
3
Conclusion
What the 502 Bad Gateway Error Is (And Why It Happens)
The 502 bad gateway error pops up from time to time, and often means there’s a problem with your server.
When you visit a website, your browser sends one or more requests to the server that hosts the site. If everything is working properly, that server will send back the information your browser asked for, and the website will load. On the other hand, the 502 bad gateway error occurs when a server sends back an ‘invalid’ response. This can mean that the connection timed out, or can be the result of several other issues.
From the Mozilla Developer Network, the official definition is:
The HyperText Transfer Protocol (HTTP) 502 Bad Gateway server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server.
So far, this may sound simple. However, the connection between your browser and most websites isn’t as straightforward as it used to be. For example, your browser’s request might get routed through a proxy server before making its way to the host in question, so it can be hard to pinpoint where the issue is located. A lot of websites also use multiple servers, which complicates things even further since any of them could be the cause of the 502 error.
All of this means there are a few potential causes for this particular error code. It could be the result of:
- Errors in your database.
- A server that is timed out, currently unavailable, or just not working as intended.
- The server is overloaded with too many requests. Perhaps a DDOS attack, or even just a larger-than-intended spike in traffic.
- A problem with your reverse proxy server.
- Faulty PHP scripts, courtesy of one of your plugins or themes.
The good news is that if the problem is server-side, you may not need to take any action. In these cases, your hosting provider will usually jump to the rescue quickly (since clients tend not to appreciate downtime). You should make sure to contact your host’s support team as soon as possible after receiving the notice that your site is affected by a 502 error.
With that in mind, we’re going to focus on what to do if the 502 bad gateway error doesn’t go away on its own quickly. Most websites can’t afford to be down for hours at a time, after all, so if this error persists it’s time to start troubleshooting on your end.
How to Fix the 502 Bad Gateway Error
Before you shift into troubleshooting mode, there’s one quick test you can run to determine if your server is responding as it should. You can try running a traceroute, to see if your server is reachable in the first place. If it is, then the problem is probably on your end. If not, this is when you may want to get in touch with your hosting provider.
You should also try resetting your router, and checking your Domain Name System (DNS) settings. These are basic fixes that can sometimes make the 502 error go away, and they’re easy enough to tackle on your own. If you find that neither solution solves the problem, however, you can use the following methods to troubleshoot the 502 error.
Clear Your Browser Cache
The 502 error can appear when you try to access your website, even if the underlying problem has been resolved. This occurs if your browser is relying on its cache, rather than loading the latest version of your site from the server.
Simply reloading the site a few times can often do the trick. Especially if you’re using the Forced Reload via Shift-CTRL-R on Windows or Shift-CMD-R on Mac.
If all of the above fails, you should proceed to empty your browser’s cache manually. Chrome users can do this by navigating to the Settings > Advanced menu, and locating the Clear Browsing Data option:
Look for the Cached Images and Files option under the Basic tab, and click on Clear Data after selecting it. Keep in mind that this menu will also delete your browsing history, if you don’t disable that setting before clicking on the Clear Data button.
This same process can also be completed using Firefox, Safari, Internet Explorer, and just about any other browser. When you have cleared the cache, try reloading your website once more. If the error persists, it’s time to get serious. For more information on clearing the cache, you can find it over at Hubspot’s hub page on the topic.
Temporarily Disable Your Content Delivery Network (CDN)
Earlier, we mentioned that your browser requests will sometimes be routed through a reverse proxy server. In other words, using a proxy server places an intermediary between the user’s browser and the website’s server.
Some services, such as Content Delivery Networks (CDN), rely on reverse proxy technology to route incoming traffic as efficiently as possible. However, sometimes this extra layer can create issues when you’re trying to connect to a website’s origin server. When that happens, your visitors (and you) might run across the dreaded 502 bad gateway error.
Fortunately, it’s easy enough to check and see if your CDN is causing this issue. All you have to do is temporarily disable the service, and then test whether your website loads correctly without it. The process of disabling your CDN will vary depending on the service you’re using, but it’s usually simple.
For instance, Cloudflare users just have to navigate to the Overview tab in their dashboard. Inside, you’ll find a list of properties that are running the service. Then you’ll need to look for the big Pause button in the Pause Website section, and click on it:
Now, when you try to access your website, its origin server will respond to the request without any middlemen getting in the way. If the 502 error is gone, then your CDN was probably the source of the issue. In most cases, you’ll just need to wait a few hours before re-enabling the service. Of course, be sure to check and make sure that the error is still gone afterwards.
If you’re using another CDN, you’ll need to look at its documentation for instructions on how to temporarily disable the service. However, if your CDN turns out not to be the problem, there’s one more fix you can try.
Test WordPress Themes and Plugins
So far, we’ve talked about three potential causes behind the 502 error: your server, your browser, and middleman services such as CDNs. That only leaves one option if you’re sure the problem is on your end, and that is your website. If you are running WordPress specifically, one of your plugins or themes might be trying to execute a script that your server can’t load correctly. This can result in an invalid response when your browser sends a request, triggering the 502 error.
You can only have one active theme at a time, so you can simply deactivate your current one and switch to a default WordPress theme temporarily, to see if that resolves the error. On the other hand, figuring out if a plugin is causing problems can take more time, depending on how many of them are currently active.
Since you don’t have access to your dashboard at the moment thanks to the error, you’ll need to disable your plugins and themes manually. Keep in mind that this process doesn’t involve deleting the plugins and themes, and reactivating them only takes a moment. So your website’s functionality shouldn’t be affected. Even so, you should have a recent backup ready just in case. If you don’t already have a backup solution in place, take a look at this list of the best WordPress backup plugins.
Then, open up the FTP client of your choice. We’re big fans of FileZilla, so we’ll be using that as our example. Log into your website via FTP, and navigate to the public_html – wp-content – plugins folder. There should be a folder for each of your installed plugins inside – even those that aren’t active:
If you right-click on any of those folders, you’ll see several options, including one labeled Rename. Click on that now, and change the name of the folder to something like disabled.pluginname:
When you access your website now, WordPress won’t be able to find that plugin, so it will load without it. If the plugin you just deactivated was causing the 502 error, your website should load correctly. Just to be sure, remember to use the CTRL + F5 command (or the OS X equivalent) to force your browser to delete its cache before reloading the site.
To avoid confusion, you should troubleshoot one plugin at a time. Change a folder’s name, try reloading your website, and see if it’s still displaying the 502 error. If it is, restore the folder’s original name. Repeat this process with each folder until you’ve found one that’s causing the error, or until you’ve tested every plugin. You can use the same process to test your active theme, which will force WordPress to use one of its default themes instead.
If one of your plugins or themes is causing the 502 error, you can delete it altogether and look for a replacement. If it’s outdated, you can also try updating it, to see if that resolves the problem. In some cases, the problem script will be patched quickly, so you can always resume using that plugin or theme later on.
Other Quick (Potential) Fixes
Now, these above fixes are likely going to find and fix the culprit if the 502 error is being caused by something on your end and not the server’s. If it doesn’t go away, remember that we suggest you contact your web host to let them sort through the server and diagnose any issues there.
That said, you can help speed up the process by performing a couple of quick checks.
The first of these checks being any logs your site might have saved. If it’s WordPress, there are a number of ways to see it. We have a solid write-up on using these logs to improve your site that may be of some help here. WP sites running versions 5.0 or greater are equipped with a Site Health tool that you can check inside your admin dashboard, so make sure you see what it has to say.
You can also make sure that your browser’s cookies are clear. These are entirely separate from the cache, and we don’t always want to clear these out. If you keep any information saved in your browser, this will wipe it out. But those same cookies may also 502 the connection between you and those sites, so it can be a Catch-22. Either way, it’s pretty easy to clear the cookies in any major browser.
If your site just stalls out, it might be that there’s something in the background that just needs more time to execute. You can increase the execution time allowed by a WordPress site pretty simply by editing your functions.php file. If you’re not on WP, you can do it via .htaccess or php.ini, too. Thimpress has a pretty good guide on how to get this all done.
Finally, you can check for DNS errors. By that, we mean that you’ve moved hosts or changed to a different kind of plan or server itself. You might have adjusted nameservers or any number of things that could go awry. DNS settings are very specific and prone to misconfiguration. So go into your cPanel or dashboard, make sure that everything lines up between your host and your domain registrar and the settings on your website itself. Sometimes a wire gets crossed or a single typo stops everything in its tracks. A little DNS proofreading can go a long way here.
And if you’re really interested in making sure the DNS is okay on your end, you can fire up the terminal and flush your DNS cache manually.
Conclusion
Troubleshooting WordPress errors is often easier than you might think. Even issues that have a lot of potential causes, such as the 502 bad gateway error, are well understood and documented. You might have to try out multiple solutions before you land on one that works, but the troubleshooting process shouldn’t take too long if you follow the right instructions.
If you run into the 502 bad gateway error on your website and it doesn’t go away after a few minutes (or after a quick call to your host’s support team), chances are the problem is on your end. Just go through the processes and tricks we mentioned above, and you and your users should be back on your website in no time.
Have you ever run into the 502 bad gateway error on one of your websites? Share your experiences with us in the comments section below!
Article thumbnail image by windwheel / shutterstock.com.
Disclosure: If you purchase something after clicking links in the post, we may receive a commission. This helps us keep the free content and great resources flowing. Thank you for the support!
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?
- Bad Gateway
- What Causes the 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.
Hello! My name is Sujay and I’m CEO of Astra.
We’re on a mission to help small businesses grow online with affordable software products and the education you need to succeed.
Leave a comment below if you want to join the conversation, or click here if you would like personal help or to engage with our team privately.
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.
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.
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!
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!
Ошибка 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 зонах
If you have a WordPress website of your own or are a regular WordPress user, you must be familiar with occasional error messages such as 502 Bad Gateway. Encountering such problems on your site can be quite frustrating and confusing for many reasons, starting from unclear causes to poor SEO rankings. However, you can quickly troubleshoot these bad gateway issues following some simple, easy steps.
When your WordPress website shows the 502 Bad Gateway error code, it is quite hard to pinpoint the exact cause of the trouble. It is usually a result of a complex, faulty connection between the user, the server, the web program, and many other external factors surrounding the web.
Even though it is difficult to understand the reasons behind this connection error, there are some tried and tested solutions to it. You can use a few simple ways to resolve 502 Gateway errors effortlessly without breaking a sweat. But before we dive into the solutions, let’s find out what this error means and some of its possible causes.
What Is A 502 Bad Gateway Error In WordPress?
A 502 Bad Gateway Error indicates that there is a problem with the website’s server communication. It is an HTTP status code that means that the web servers did not properly process your request for a certain action.
According to the Internet Engineering Task Force (IETF), a 502 Bad Gateway Error is a status code that indicates the server received an invalid response from an inbound server it accessed while attempting to fulfill the request.
In simpler words, every time you visit a website, your browser sends a request to the webserver. After processing the request, the webserver “returns” the requested data along with an HTTP status code and HTTP header.
This is where the 502 (Bad Gateway) error comes in. It indicates that your browser’s web server while acting as a gateway to relay information and data from another server, has received an invalid or faulty response.
Types Of 502 Bad Gateway Errors
Website designers can customize what a 502 Bad Gateway Error will look like depending on the various web browsers, servers, and operating systems. There may be multiple names and visualizations for it on different websites, but they all point to the same error.
You might have seen this server communication error named as one of the following:
⚠️ “502 Bad Gateway”
⚠️ “Error 502.”
⚠️ “HTTP Error 502 – Bad Gateway”
⚠️ “502 Service Temporarily Overloaded”
⚠️ “HTTP 502.”
⚠️ Temporary Error (502)
⚠️ 502. That’s an error
⚠️ “502 Server Error: The server encountered a temporary error and could not complete your request.”
Some web pages simply put up the error code while others, like Twitter, show a completely customized heading and image to imply excessive traffic on site.
Possible Causes Of 502 Bad Gateway Error
As mentioned earlier, there isn’t a specific reason behind 502 Bad Gateway Errors. Instead, there are a handful of possibilities that may lead to miscommunication between web servers.
🎯 A Server Overload
When a website is overcrowded with far more traffic than usual, it reaches its memory capacity and gets overloaded. It can cause server communication issues and occasional server crashes.
🎯 Network Errors
Several network errors, including potential DNS changes, routing issues, and ISP-related problems, may trigger 502 Gateway Errors on your WordPress website.
🎯 Blocked Server Transmission By Firewall
A firewall is used to protect your websites and content from potentially harmful traffic. However, a Firewall may sometimes mistake safe content as malicious and prevent traffic from getting through.
🎯 Faulty Programming
The simplest issue that results in 502 Bad Gateway errors on your websites may be faulty programming. If your WordPress website has internal errors with its codes, servers will not be able to connect and display any content.
🎯 Server Software Timeouts
If a server takes too long to load, it may result in the caching tool reaching its timeout limit and trigger server gateway errors.
Ways To Resolve 502 Bad Gateway Errors In WordPress With Few Easy Steps
A 502 Bad Gateway Error is usually a problem that arises from network or server errors. However, it might also be the result of simple connectivity issues on the user end.
In this blog, we will look at some quick fixes to all your Bad Gateway errors in WordPress that will work perfectly for WordPress owners and WordPress website users.
✅ Refresh And Reload The Web Page
502 (Bad Gateway) errors usually result from temporary issues in server connectivity. As mentioned earlier, this can be due to a surge in website traffic that overloads the site and the server. In such cases, the easiest solution can be to reload the web page simply.
When encountering Bad Gateway errors, the first thing you should do is to wait a minute or so and then hit a refresh (or F5 or Ctrl+F5) on your web page. If it isn’t a significant problem with the server or the connectivity, this is sure to get your WordPress website running again.
✅ Look For Any Server Connectivity Issues
Server maintenance is the process of keeping the server software up to date and running. It is essential to prevent network failures and to ensure your computer network can operate smoothly.
However, the whole process can be time-consuming and render your website down for the time being. During server maintenance, you and your website visitors can come across 502 Bad Gateway errors that will prevent you from accessing the site.
At times like this, the only way to troubleshoot this problem is to wait and allow your server to finish maintenance. You can access the site after hitting refresh or trying to enter the site again a short while later.
✅ Try To Load The Site On A New Browser
Sometimes the browser you use may fail to detect connectivity with web servers and trigger a Bad Gateway error on your WordPress websites. It is challenging to notice such minor issues caused by your browser.
Hence, if you come across a 502 Bad Gateway Error message on your web page, you must try to load your site on a new or different browser. You can also try opening your website in an incognito window. If the problem arising is browser-related, using a new browser will definitely allow you to connect to your website.
✅ Clear The Browser Cache And Cookies
Caches are usually used to create a static version of websites, which reduces the back and forth communication between a web browser and a database server. Caches are meant to improve website speed and site performance. Caching also ensures less load on your hosting servers.
On the other hand, website cookies or HTTP cookies are small pieces of data stored on a site user’s device to keep track of their activities. Cookies help to serve up targeted information to your users.
However, when web browsers, such as Chrome and Firefox, store outdated information in their cache and cookies, they can cause server miscommunications that result in bad gateways and 502 errors.
If your WordPress website shows 502 Bad Gateway errors, you can clear your browser caches and cookies. This will not only help to resolve bad gateway errors but also make your website run faster.
To learn more about WordPress caches and how to remove them, we recommend you read this blog.
✅ Use A VPN To Access Your Website
Various online VPNs facilitate creating an encrypted connection between your browser and a remote server, which tunnels all your website traffic. Since your browser uses an encrypted server link, your network IP address is hidden, masking your identity and location to ensure privacy.
If 502 bad gateway errors appear on your WordPress website due to server or ISP errors, you can try to reroute your connection using Virtual Private Networks (VPNs). This way, your WordPress website will be connected to a new server, and gateway errors will be resolved immediately.
✅ Restart All Your Networking Equipments
Sometimes, it is not your web server that is faulty or causes a bad gateway connection. If you test your server and determine that the 502 Bad Gateway Error persists, it might be due to a bad connection on your network’s part and not a result of faulty server responses.
This can happen through possible temporary connection errors on your computer or your networking equipment, such as your wifi, router, modem, etc. A simple restart of your computer and your networking devices might be the solution to any bad gateway errors.
✅ Update WordPress Plugins, Themes, And Extensions
It is also important to check your WordPress website plugins, themes, and extensions. Wrong codes due to third-party plugins and themes and issues with misconfigured caching plugins often lead to bad server gateways and 502 errors on your website.
To make sure your WordPress plugins are not causing server communication errors on your website, you can deactivate and then update your plugins. If this fixes the server error, the problem was with one of your plugins. You can quickly determine which plugin was the faulty one by reactivating them, one at a time.
If the issue still does not get resolved, you need to follow similar steps with your WordPress themes and extensions. You can update and re-activate them to troubleshoot any server communication difficulties.
✅ Temporarily Disable Your CDN And Firewall Connection
If you are using a third-party content delivery network (CDN) or a website firewall, chances are that they are causing bad gateway communication due to faulty configurations. Some providers offer complete proxy services with extra firewalls or DDoS protection.
A defective firewall configuration can cause requests from a content delivery network to be interpreted as an attack on your server and rejected, resulting in a 502 Bad Gateway Error. It’s also possible that your WordPress security plugins will prevent contact between the servers or even block your local or ISP IP address.
To troubleshoot this issue, you will simply have to disable your firewall connection temporarily. Doing so will remove any extra layer of protection between your browser and the hosting server and should get your website connection back on track. You will be able to disable your firewall via your protection provider’s admin console.
However, it can be risky to disable your firewall protection because it can make your device or network vulnerable to unauthorized access from online. So you need to be extra careful if you want to try this method.
✅ Check For DNS Issues And Change DNS Server
A 502 Bad Gateway Error can also result from a DNS issue. The domain might not respond to the correct IP address, or the DNS server might not be responding. If you’ve recently changed host servers or transferred your website to a different IP address and can make changes to your website’s DNS server.
Migrating from one DNS server to another involves reconfiguring the server, and this might take up to 48 hours to propagate fully. In this case, you will have to wait for the propagation to complete.
You can also try to flush your DNS cache or change your DNS server if it is not done earlier.
✅ Restart PHP To Resolve Any PHP Timeout Issues
If you’re importing a large number of WordPress files, you could get an error 502 bad gateway as a result. This happens when a single PHP process runs longer than it should.
You can contact your web host and find out the maximum time set in your PHP configurations and increase it if needed. Restarting PHP can also be helpful. However, if you want to do it correctly, you can contact the WordPress support team.
What To Do If All Attempts Fail And 502 Bad Gateway Error Persists?
If the 502 Bad Gateway errors persist after trying all of the procedures mentioned above, we recommend contacting your web host and asking for help. They will surely know what to do and will be able to inspect their server problem logs or have their own backups of your WordPress site, for example.
Effortlessly Troubleshoot 502 Bad Gateway In WordPress
As you can see, there are multiple ways to troubleshoot 502 Bad Gateway errors in WordPress. Although a server usually causes such issues, there is still something you can do on your end to resolve the issue. We hope that these quick fixes will help you resolve any 502 errors and ensure a smooth browsing experience on WordPress.
If you found this blog helpful, let us know by commenting below; we would love to know! To get more useful tips like these, please subscribe to our blogs and join our friendly Facebook community.
Post Views: 866
Do you want to fix the 502 bad gateway error on your site? This error is quite annoying because it can be caused by a lot of different things. This means troubleshooting the 502 bad gateway error can take some time. In this article, we will show you how to easily fix the 502 bad gateway error in WordPress.
What is a 502 Bad Gateway Error?
A 502 bad gateway error is triggered when your WordPress hosting server gets an invalid response for the requested page.
Bad gateway error is one of the common WordPress errors that you may encounter on your site. It can be caused by a number of reasons and depending on your server the error message may also differ in looks slightly.
When you visit a website your browser sends a request to the hosting server. The hosting server then finds the page and sends it back to your browser with the status code.
Normally, you wouldn’t see this status code. However, in case of an error the status code is displayed with an error message. Examples of such errors include 404 not found, 503 service unavailable, 403 forbidden error, and more.
The most common reason for a 502 bad gateway error is when your request takes too long for the server to respond. This delay can be a temporary glitch caused by high traffic. It could also be a glitch caused by a poorly coded WordPress theme or plugin. Last but not least, it can also happen due to a server misconfiguration.
That being said, let’s take a look at how to easily fix the 502 bad gateway error in WordPress.
Fixing the 502 Bad Gateway Error
This error is usually caused when your server is unable to find the cause of the invalid response. This means that we will try different troubleshooting steps until we find the problem.
Ready, let’s get started.
Step 1: Reload Your Website
Sometimes your server may take longer to respond due to increased traffic or low server resources. In that case, the problem may automatically disappear in a few minutes. You should try reloading the web page that you are viewing to see if this was the cause.
If this fixed your problem, then you do not need to read any further. However, if you see this error frequently, then you need to continue reading as there may be something else that needs fixing.
Step 2: Clear Browser Cache
Your browser may be showing you the error page from the cache. Even after the issue is fixed, you would see the 502 error because the browser is loading your website from cache.
To fix this, users with Windows/Linux operating systems can press Ctrl + F5 buttons and Mac OS users can press CMD + Shift + R buttons on their keyboards to refresh the page. You can also remove the cache manually from your browser settings.
Once you clear your WordPress cache, try loading the website again.
You can use a different browser to troubleshoot if the problem is occurring because of browser cache. If you see the error on all browsers, then continue reading.
Step 3: Disable the CDN or Firewall
If you are using a CDN service or website firewall on your website, then it is possible that their servers are acting up. To check this, you will need to temporarily disable CDN.
Once disabled, it will remove the additional layer that has been created between your browser and the hosting server. Your website will now load entirely from your server and if the issue was caused by the CDN / firewall service, then it will get resolved now.
You can then contact your CDN service provider for support. Once the issue is resolved, you can go ahead and enable the CDN again.
Step 4: Update WordPress Themes and Plugins
If the error is still there, then the next step is to check your theme or plugins.
First, you will need to deactivate all WordPress plugins via FTP. After that, visit your website to see if the error has resolved.
If it is, then one of your plugins was causing the issue. You now need to activate all plugins one by one until you can reproduce the error. This will help you locate the plugin responsible for the error.
You can find an alternative plugin or contact the plugin author for support.
If deactivating plugins didn’t solve your issue, then you would want to check your WordPress theme. You will need to switch WordPress theme via phpMyAdmin.
After switching your theme to the default WordPress theme, visit your website to see if it’s working. If you are still seeing the error, then continue reading.
Step 5: Check the Hosting Server
If all above-mentioned troubleshooting steps failed, then it is likely an issue with your hosting server.
You need to contact your hosting provider’s support team and let them know the issue. You can also mention all the troubleshooting steps you have taken.
All good WordPress hosting companies will be able to quickly fix the issue if it is caused by a server misconfiguration.
That’s all. We hope this article helped you learn how to fix the 502 bad gateway error in WordPress. You may also want to see our complete WordPress troubleshooting guide for step by step instructions on fixing your WordPress issues.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.
Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.
There are numerous errors that usually appear on your WordPress site, but one of the most frustrating and annoying errors is “502 Bad Gateway Nginx”.
Before we learn how to fix it, though, we need to understand 502 bad gateway WordPress, what it means, and how it appears on your browser. Once you understand why it shows up for your website or any other site that you visit, fixing WordPress 502 error will be a lot easier.
What does 502 Bad Gateway Error Mean?
502 bad gateway error is a server error that appears when your web server doesn’t send any response to your browser or is unable to establish a connection with your browser.
Whenever a client/user visits a website, the browser sends an HTTP request to the webserver. The web server processes the request, initiates action and sends an HTTP response to your browser. That’s when the site’s content appears on your browser.
But, when the web server sends an invalid response or none at all, then instead of serving your web content, it displays the dreaded 502 bad gateway error on the browser.
Different web server displays this error in different ways. Sometimes you will see the error like this:
- 502 Bad Gateway Nginx
- Temporary Error 502
- Error 502
- 502 Server Error
- HTTP 502
- White Screen
- 502. That’s an error
- 502 Proxy Error
- HTTP Error 502 – Bad Gateway
- 502 Server Error: The server encountered a temporary error and could not complete your request
In essence, 502 bad gateway is a server-level misconfiguration but sometimes it appears due to other factors like when your web server takes too much time to respond due to a poorly coded theme or plugin installed in your WordPress site. It can also appear due to high traffic on your Website, server connection break, DNS issue, browser cache or other reasons.
So now that you know what 502 Bad Gateway error means, I’m going to show you some popular and effective hacks through which you can easily fix the 502 Bad Gateway error.
How to Fix a 502 Bad Gateway WordPress Error?
Whenever I’ve faced a 502 error in WordPress, there are 7 hacks that I usually try and fix this issue. Similarly, you can also use the following methods to troubleshoot the 502 error:
1. Try Reloading the Page
When any WordPress site faces high traffic, the server gets overloaded and displays this error. You need to wait for a few minutes and then try reloading the page because this error is temporary and automatically resolves in a few minutes.
If this works then you don’t need to read further. But if it doesn’t, then check the other solutions as well.
You can also check your website on https://downforeveryoneorjustme.com/ to check if it’s down for you only or for everyone else.
2. Clear Browsing Cache
When you visit any website, your browser saves its content and data in the cache to reduce page load time when you visit that site again.
Similarly, your browser stores the 502 error content and data in the cache and displays the error page again and again. If you simply clear the cache, it might solve the issue straight away.
3. DNS Issue
If you’ve recently migrated your WordPress site to a new host then you might see the 502 bad gateway error. Basically, website migration takes time, around 24 to 32 hours to fully move your website to a new host, hence you need to wait for the time period and check your website again.
4. Disable CDN
A CDN or Content Delivery Network is a system of networks that stores static data on your website. It’s an extra layer between the server and browser that helps boost your site speed. If you’re using a CDN service on your WordPress site, it’s possible that the “error 502” is caused by its services.
If that’s the case, you need to disable your CDN. Once disabled, visit your WordPress site and see if the error is resolved or not.
If the error is resolved, then contact your CDN providers for support because there’s an issue with your CDN service that’s causing this error. If the error persists, keep reading to find out what you can do further.
5. Check your Plugins and Themes
Poorly coded plugins or themes are one of the most common reasons that cause Error 502. First, you need to find out which plugin is causing this error and for this, you need to access your web server via an FTP client and deactivate all the WordPress plugins.
Open FileZilla FTP client and fill the respective fields to access your web server, then go to your plugins directory through applications > (your DB folder) > public_html > wp-content and rename the plugins folder to anything you like. I changed it to “Originalplugins”.
Create a new empty folder/directory and name it “plugins”.
The plugins folder is empty and the Originalplugins folder contains all the plugins.
Now visit your WordPress site, and if it runs without the error then it means one of your plugins caused this error.
Next, you need to delete the empty plugins folder and change the name of the “Original plugins” folder to “plugins”.
You will see that all the plugins are deactivated. Start activating the plugins one by one and visit your website after each until you catch the plugin that’s causing the error. Once you find the culprit, you can either use an alternative plugin, or you can contact the current plugin’s support to resolve the issue.
If this doesn’t solve the issue as well, you need to check for a faulty theme. For this, you need to change the name of the activated theme folder name to anything that you like and follow the same steps that we used for the plugins.
Now visit your website, if you see a white screen then it means your theme is faulty. Just login to your wp-admin and activate the default theme.
6. Increases PHP Execution Time
If even that doesn’t fix the error, then it’s time to check PHP execution time, which is a common reason that causes 502 bad gateway errors in WordPress. You can resolve this issue by increasing the PHP execution time. For this, you need to access the .htaccess file via FTP and paste the following code or change the previous code with this to increase the max execution time and max input time.
- php_value max_execution_time 300
- php_value max_input_time 300
Recommendation:
- Set the max execution 300 sec (5 mins) and above for large and high traffic websites
- Set the max execution 300 sec (5 mins) and below for small and low traffic websites
7. Checking Hosting Server
If all the above solutions aren’t working and you still have a 502 bad gateway WordPress error on your web site then you need to check your hosting service. Contact your hosting provider’s support and they will help you resolve server misconfiguration issues.
Conclusion
Now you know what WordPress 502 bad gateway error means and that it’s a server-side error and appears on your website due to high traffic, PHP timeout, DNS issue, and other reasons. The above-mentioned solutions, though, can help you easily fix 502 bad gateway errors.
I hope this tutorial helped you learn “How to fix 502 Error in your WordPress site?”
If you found this tutorial useful, don’t forget to share it in your circle. And of course, if you need guidance on anything related to WordPress, just comment below or you can email me at [email protected]