Adding an API Gateway to your application is a good way to centralize some work you usually have to do for all of your API routes, like authentication or validation. But like every software system, it comes with its own problems. Solving errors in the cloud isn’t always straightforward, and API Gateway isn’t an exception.
What is AWS API Gateway?
AWS API Gateway is an HTTP gateway, and as such, it uses the well-known HTTP status codes to convey its errors to you. Errors in the range of 400 to 499 usually point to a problem with the API client, and errors in the range of 500 to 599 mean something on the server is wrong.
This is a rule of thumb, and if you don’t have any logic bugs in your backend, it holds. But nobody is perfect, and so it could happen that a 400 code still means your client is right and your backend is wrong. But let’s not get ahead of us and look into the errors, case by case.
API Gateway Error Codes
Here’s a table summarizing common errors encountered in AWS API Gateway:
Error | Description |
---|---|
400 Error: Bad Request | This error is often due to invalid JSON, missing fields, wrong data types, or invalid characters in the API request. |
403 Error: Access Denied | This error, also known as “Forbidden,” usually arises from permission issues related to the IAM role of the API Gateway or AWS Cognito. |
404 Error: Not Found | This error typically indicates an incorrect URL or an attempt to access non-existent data in the services integrated with API Gateway. |
409 Error: Conflict | This error indicates a conflict with a resource’s current state, often related to a caller’s reference. |
429 Error: Limit Exceeded | This error signals that you’ve exceeded an API quota, often due to the usage limit of an API key. |
500 Error: Internal Server Error | This is a catch-all error and could imply a buggy code, inconsistent error mapping, or other technical issues. |
502 Error: Bad Gateway | This error suggests a problem with the service integrated with your API Gateway, like connection issues or invalid response structures. |
503 Error: Service Unavailable | A common error that signifies the service took too long to respond. |
504 Error: Endpoint Request Timed-out | This error could indicate DNS or network problems, often arising when an integrated service isn’t running or IP/hostname is incorrect. |
Handling API Gateway issues is a significant part of ensuring smooth operation of your services. For more in-depth information on each error, click on the error code to read more. Don’t forget to monitor your system carefully and investigate promptly when you encounter these error codes.
Monitoring AWS API Gateway
We went over all the API Gateway errors you will probably encounter, and like with anything debugging-related, things can get quite messy — especially if you have countless rows of logs to sift through.
The good news is that Dashbird integrates well with API Gateway monitoring and delivers actionable insights straight to your Slack or SMS when things go awry.
Dashbird also works with AWS as their Advanced Technology Partner and uses the AWS Well-Architected Framework to ensure you’re on track to performance and cost optimization. If you want to try Dashbird out, it’s free for the first 1 million invocations per month.
Read our blog
4 Tips for AWS Lambda Performance Optimization
In this article, we’re covering 4 tips for AWS Lambda optimization for production. Covering error handling, memory provisioning, monitoring, performance, and more.
AWS Lambda Free Tier: Where Are The Limits?
In this article we’ll go through the ins and outs of AWS Lambda pricing model, how it works, what additional charges you might be looking at and what’s in the fine print.
AWS Lambda vs EC2: A Comparative Guide
More articles
Загружая страницу, браузер отправляет кучу запросов другим серверам. Они обрабатывают все запросы, затем возвращают код ответа HTTP с определенным результатом. Если в процессе этого возникнет какой-то сбой, на экране браузера отобразится ошибка. И одна из таких ошибок – 502 Bad Gateway. Я расскажу, что она означает, по каким причинам выходит, а еще опишу способы ее устранения.
Что означает ошибка 502 Bad Gateway
Ошибки, принадлежащие серии 5xx, означают появление проблем на стороне сервера. Если взять конкретно ошибку 502 Bad Gateway, то ее появление будет означать получение неправильного ответа сервера. «Виновниками» в такой ситуации обычно являются прокси, DNS или хостинг-серверы.
Причины возникновения ошибки
Наличие ошибки 502 Bad Gateway может быть связано с несколькими причинами. Рассмотрим наиболее встречаемые:
-
Высокая загрузка сервера. Если сервер перегружен большим количеством запросов или ресурсов, то он может стать временно недоступным. В этом случае попробуйте повторить запрос позже, когда нагрузка снизится.
-
Сетевые проблемы. Ошибка 502 может возникать из-за проблем в сети – возможно, соединение было разорвано или возникли проблемы с маршрутизацией. Рекомендуется перезагрузить роутер, чтобы устранить ошибку. Если проблема сохраняется, то лучше связаться с интернет-провайдером для получения помощи.
-
Проблемы с DNS. Если сервер не может разрешить DNS-имя, например, когда неверно настроены DNS-серверы или отсутствует соответствующая запись, то это может вызвать ошибку.
-
Хакерская атака. Злоумышленники могут использовать DDoS-атаку на сайт в своих личных целях. Суть атаки в имитации большого наплыва пользователей – чересчур высокий поток может обеспечить возникновение кода 502.
-
Ошибки в коде сайта. Часто бывает и такое, что на сайте используется неправильно написанные функции и иные строчки кода, в результате чего появляется ошибка 502. Также это может быть связано с недавно загруженными плагинами или выходом из строя уже имеющихся.
-
Проблемы с браузером. Если вы пользователь, то виной ошибки может быть собственный браузер. Как правило, связано это с установленными расширениями. Поочередное отключение плагинов поможет выявить наличие кода 502.
Чем отличается ошибка 502 Bad Gateway Nginx
Если вы столкнулись с ошибкой 502, то она может идентифицироваться как Bad Gateway Nginx или Bad Gateway Apache. Отличий как таковых нет, разные названия лишь говорят о том, какой именно используется веб-сервер, который применяется для снижения нагрузки на сервер, аутентификации пользователей и многого другого. Именно он информирует о наличии кода 502, поэтому вы можете встретить в описании слова Nginx и Apache. Это наиболее популярные веб-серверы.
Комьюнити теперь в Телеграм
Подпишитесь и будьте в курсе последних IT-новостей
Подписаться
Что делать, если вы пользователь
Ошибка 502 Bad Gateway может появиться на любом сайте. Пользователю для начала следует проверить, не является ли причиной проблемы какие-то неполадки с его стороны. Сделать это можно указанными ниже способами.
Перезагрузить страницу
Возможно, на момент загрузки число запросов на сайт превышает определенный лимит, устанавливаемый владельцем сайта. Если это действительно так, тогда простая перезагрузка страницы вполне будет уместна. Я рекомендую обновить страницу как минимум три раза в течение 2-3 минут и только потом приступать к следующим способам.
Проверить подключение к интернету
Стоит проверить работу модема и попробовать загрузить другие страницы. Убедитесь, что подключение к интернету стабильное. Еще вариант – перезапустить маршрутизатор и попробовать снова загрузить проблемный сайт.
Очистить кэш и cookies
Нередко причиной появления данной ошибки могут быть неверно загруженные cookies и кэш. В таких случаях необходимо просто очистить данные в настройках интернет-обозревателя.
Для любого браузера актуально – зайти в историю просмотров и найти ссылку «Очистить историю». В новом окне отметить пункты с кэшем и cookies, затем подтвердить действие. Как только данные будут удалены, надо вновь попробовать загрузить страницу. Не помогло? Идем дальше!
Очистить кэш DNS
Допустимо, что в кэше установлено неправильное значение IP-адреса. Для таких случаев можно использовать сброс DNS кэша. В зависимости от операционной системы кэш DNS очищается по-разному. Давайте рассмотрим ниже, какие нужно выполнять действия под конкретную ОС.
Windows
Очистка кэша на Windows выполняется через командную строку. Для этого необходимо сделать следующее:
1. Открываем меню Пуск и вводим запрос «Командная строка». В отобразившемся окне запускаем нужный инструмент.
2. Следующим шагом вводим запрос ipconfig /flushdns и ожидаем окончания работы приложения. Должна появиться надпись «DNS успешно очищен».
После выполнения этой процедуры попробуйте повторно зайти на сайт – проблема с ошибкой должна решиться.
Mac
В данном случае нужно будет воспользоваться терминалом:
1. Используем комбинацию клавиш Command + Space, затем находим и открываем приложение «Терминал».
2. В отобразившимся окне вводим команду sudo killall -HUP mDNSResponder и ожидаем окончания работы инструмента.
Linux
Здесь так же, как и на MacOS, нужно воспользоваться встроенным приложением «Терминал» – открываем его с помощью комбинации клавиш «Ctrl+Alt+T» и вводим необходимую команду. Она может отличаться в зависимости от типа операционной системы.
Для Ubuntu:
sudo service network-manager restart
Для других дистрибутивов:
sudo /etc/init.d/nscd restart
Попробовать зайти с другого браузера
Проблема 502 Bad Gateway может быть актуальна и для конкретного браузера. Если у вас на компьютере есть другой интернет-обозреватель, попробуйте открыть сайт через него.
Отключить плагины и расширения
На загрузку некоторых страниц могут влиять установленные в браузер плагины и расширения. Особенно это касается VPN-сервисов и блокировщиков рекламы. Попробуйте поочередно отключать их и перезапускать страницу. Не исключено, что виновник будет найден.
Зайти на страницу позже
Когда ничего из вышеперечисленного не помогло, значит, проблема все же кроется на стороне сервера. Вам остается только подождать некоторое время, пока разработчики не устранят ошибку на сайте. Вы также можете написать владельцу и сообщить о проблеме.
Читайте также
Что делать, если вы администратор сайта
Обычно такие проблемы самостоятельно решать не рекомендуется. Лучше сразу же обратиться в службу технической поддержки и описать проблему. Но есть пара действий, которые все же могут помочь определить источник проблемы.
Проверка журнала ошибок
Актуально в случаях, при которых ошибка 502 Bad Gateway появляется после внесения изменений или обновления. Определить это очень просто, нужно лишь проверить журнал ошибок. В CMS WordPress можно включить запись возникающих ошибок, добавив в файл wp-config.php вот такие строки:
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false );
После этого все записи начнут отображаться в файле debug.log. Храниться он будет в директории wp-content. Понадобится некоторое время, чтобы причины ошибок были записаны. Потом можно тщательно изучить записи и уже на основе их предпринимать конкретные изменения.
Проверка плагинов
Следует проверить, не влияют ли какие-либо плагины на работу сайта. Для этого можно поочередно отключать их, просто переименовывая папку интересующего плагина. Для этого надо выделить папку, затем нажать на меню «Файл» и в нем выбрать пункт «Переименовать».
Проверка сети CDN
Сети CDN и службы предотвращения DoS тоже могут влиять на работу сайта. Обычно виновник проблемы указывается на странице с кодом ошибки. Например, если под кодом 502 Bad Gateway есть строка cloudflare-nginx, значит, для исправления ошибки надо обратиться в службу поддержки CloudFlare. Можно отключить данный сервис, но потом придется долго ждать обновления DNS (это может занять несколько часов).
Отключение anti-DDos
Отключение защиты от DDoS-атак может быть одной из возможных причин возникновения ошибки 502 Bad Gateway. Обычно анти-DDoS-системы используются для обнаружения и снижения воздействия DDoS-атак, которые направлены на веб-сервер. Однако иногда эти системы могут неправильно работать или применять слишком строгие фильтры, что может привести к блокировке допустимого трафика и, как результат, к ошибке 502.
Если вы столкнулись с подобными проблемами после отключения анти-DDoS-защиты, рекомендуется выполнить следующие действия:
-
Изучите конфигурацию anti-DDoS. Если у вас есть доступ к настройкам анти-DDoS-системы, проверьте их на предмет возможных проблем или ошибок. Убедитесь, что фильтры правильно настроены и не блокируют трафик.
-
Свяжитесь с провайдером услуг анти-DDoS. Расскажите о проблеме, которую вы испытываете, и попросите проверить конфигурацию системы или предоставить рекомендации по ее настройке.
-
Улучшите настройки анти-DDoS-системы. Обратитесь к документации или технической поддержке поставщика системы для получения инструкций по оптимальной конфигурации.
-
Используйте альтернативные методы защиты от DDoS. Если проблемы с anti-DDoS продолжаются, возможно, вам придется искать альтернативные методы защиты от DDoS-атак. Обратитесь к специалистам по безопасности или провайдерам услуг для получения рекомендаций и реализации более надежных мер безопасности.
Увеличение количества ресурсов
Еще одной причиной появления ошибки 502 Bad Gateway может быть увеличение количества ресурсов сервера. Вот с чем можно столкнуться:
-
Неправильная конфигурация. При увеличении количества ресурсов, таких как процессорное время, память или сетевая пропускная способность, необходимо также правильно настроить сервер, чтобы он мог эффективно использовать эти ресурсы. Рекомендуется проверить конфигурацию сервера и приложения, а также убедиться, что они соответствуют увеличенным ресурсам.
-
Недостаточная инфраструктура. Увеличение количества ресурсов может потребовать более мощной инфраструктуры, чтобы обрабатывать дополнительную нагрузку. Если сервер или сетевая инфраструктура не могут эффективно обслуживать увеличенное количество запросов или обрабатывать более высокую нагрузку, это может привести к ошибке 502.
-
Проблемы с распределением нагрузки. Если вы используете балансировку нагрузки для распределения запросов между несколькими серверами, увеличение количества ресурсов может потребовать соответствующих настроек и обновления балансировщика нагрузки.
-
Проблемы с базой данных. Проверьте настройки и производительность БД, а также убедитесь, что она способна обслуживать увеличенный объем данных и запросов.
Ошибка 502 на виртуальном хостинге VPS/VDS
Ошибка 502 Bad Gateway возникает из-за превышения лимита трафика пользователей, «шалостей» бота, скачивания сайта или даже DoS‑атаки. Решение данной проблемы кроется в ограничениях памяти.
Запустить команду top
Данный запрос в терминале поможет установить наличие свободной памяти. Этим же способом можно проверить, работает ли Apache.
Посмотреть логи Apache и nginx
Обычно в этих логах отображается активность пользователей. Если есть что-то подозрительное, можно предпринять действия. К примеру, забанить определенные IP-адреса, настроить Fail2ban или подключить систему защиты от DoS-атак.
Если после этого количество запросов к серверу снизилось, необходимо перезапустить Apache.
Увеличить объем памяти
Бывает, что с логами все нормально, но памяти на обработку запросов все равно не хватает. Узнать об этом просто – при проверке командой top будет выдана ошибка OOM (out of memory). В таких случаях можно просто увеличить ее объем. Можно просто заказать другой тариф, в котором количество предоставляемой памяти больше. Подробнее об этом.
Проверить лимиты на php-cgi процессы
Если после проверки командой top показано, что свободной памяти еще достаточно, значит, на php-cgi процессы установлены лимиты. Для решения надо открыть конфигурационный файл Apache – httpd.conf, найти секцию модуля FastCGI (mod_fascgi или mod_fastcgid) и увеличить лимит.
Обратиться к службе технической поддержки
Если вышеперечисленные способы исправления ошибки 502 на виртуальном сервере не помогут, придется обращаться в техподдержку хостинга. При этом обязательно надо упомянуть, что вы уже предприняли и как проводили все действия.
Влияние 502 на SEO
Ошибка 502 Bad Gateway – это временная проблема, когда сервер, выступая в роли шлюза или прокси, не может получить ответ от сервера, к которому он обращается. Несколько кратковременных ошибок 502 не должны существенно влиять на SEO, так как поисковые роботы обычно понимают, что это временное состояние. Однако частые и продолжительные ошибки могут негативно сказаться на SEO и привести к потере индексации страниц и плохому пользовательскому опыту. Чтобы минимизировать негативное влияние на SEO, рекомендуется проводить регулярный мониторинг веб-ресурса и оперативно решать проблемы, связанные с появлением ошибки 502.
О чем речь? Если сервер, с которым связывается ваше устройство, получает некорректный ответ от сервера уровнем выше, на экране компьютера или смартфона высвечивается ошибка 502 Bad Gateway, делая работу невозможной.
На что обратить внимание? Проблема чаще всего возникает из-за сбоев в функциях DNS, прокси или хостинга. Но ситуация поправима, причем сделать это может не только администратор ресурса. Зачастую хватает и грамотных действий обычного пользователя.
В статье рассказывается:
- Общая характеристика ошибки 502 Bad Gateway
- Причины возникновения ошибки 502
- Советы пользователю по исправлению ошибки 502
- Рекомендации администратору по исправлению ошибки 502
-
Пройди тест и узнай, какая сфера тебе подходит:
айти, дизайн или маркетинг.Бесплатно от Geekbrains
Общая характеристика ошибки 502 Bad Gateway
Любой сайт состоит из большого количества файлов: CSS-стили, коды, медиаконтент, HTML-документы и т. д. Все эти данные хранятся на веб-сервере. Чтобы открыть страницу и получить доступ к контенту, браузер направляет запрос на сервер. Если ответ на него по каким-либо причинам не поступает, появляется ошибка сервера 502.
В переводе ошибка 502 Bad Gateway означает «плохой шлюз», соответственно, проблема на шлюзе, в роли которого выступает прокси-сервер. То есть баг возникает в случае, если прокси не может получить данные от источника. Код состояния HTTP 502 веб-сервер использует для описания ошибки.
Проблема может распространяться как на весь сайт полностью, так и на отдельные его страницы. В зависимости от программы, которая была использована для создания веб-сервера, у ошибки 502 есть две основные разновидности – Bad Gateway Nginx или Bad Gateway Apache. Причины возникновения проблемы при этом одинаковы.
Также эта ошибка может иметь и другие формулировки:
- Error 502.
- Bad 502 Gateway.
- 502 Error.
- 502 Proxy Error.
- Bad Gateway: Registered endpoint failed to handle the request, Temporary Error (502).
- That’s an error.
- 502 Service Temporarily Overloaded.
- 502 Server Error: The server encountered a temporary error and could not complete your request.
- 502 – Web server received an invalid response while acting as a gateway or proxy server.
- HTTP 502.
- HTTP Error 502 Bad Gateway.
Топ-30 самых востребованных и высокооплачиваемых профессий 2023
Поможет разобраться в актуальной ситуации на рынке труда
Подборка 50+ бесплатных нейросетей для упрощения работы и увеличения заработка
Только проверенные нейросети с доступом из России и свободным использованием
ТОП-100 площадок для поиска работы от GeekBrains
Список проверенных ресурсов реальных вакансий с доходом от 210 000 ₽
Уже скачали 22620
Между сервером и браузером может стоять веб-сервер, который хранит файлы сайта и используется для снижения нагрузки. Он находит необходимую страницу в каталоге и отправляет ее в ответ на запрос пользователя. Обозреватель обрабатывает полученный файл и отображает его на экране. Так как веб-сервер выступает посредником между браузером и сервером, то именно он оповещает пользователя о проблеме.
Чаще всего причиной ошибки 502 при открытии сайта является перегрузка сервера, которая может возникнуть по ряду причин:
- Большое количество посетителей одновременно. Возможности сервера ограничены, потому просматривать сайт может лишь определенное количество пользователей. Максимальное число зависит от мощности сервера и настроек, которые установил владелец ресурса. Если одновременно на сайт зайдет слишком большое количество пользователей, то сервер не выдержит нагрузку, и страница выдаст код ошибки 502. Например, такие ситуации часто случаются в интернет-магазинах в период акций и сезонных распродаж.
- Хакерская атака (DDoS-атака). Хакеры, создавая большое количество запросов, имитируют огромный наплыв пользователей, вследствие чего сервер перегружается и выходит из строя.
- Плохая оптимизация сайта. Если настройки площадки выставлены таким образом, что небольшое количество посетителей генерирует много запросов, то в таком случае следует оптимизировать работу сервера с пользователями.
- Действия соседей по виртуальному хостингу. Если вы пользуетесь виртуальным хостингом, то мощность веб-сервера делится на всех его арендаторов. В случае возникновения проблем у одного из сайтов возрастет потребляемая им мощность. Оставшейся части ресурсов может быть недостаточно для корректной работы других участников хостинга, и сайт выдаст номер ошибки 502.
Читайте также
Еще одной причиной возникновения такого бага может быть некорректная работа PHP-скрипта. Неверно настроенные плагины могут выдавать ошибку сайта 502.
Также причиной может являться баг браузера. Проблема может быть на стороне пользователя в случае, если у него установлены расширения, нарушающие соединение с сервером сайта.
Советы пользователю по исправлению ошибки 502
Ошибка 502: что делать?
- Перезагрузите страницу. В случае если проблема возникла по причине большого наплыва посетителей, через некоторое время количество пользователей может сократиться, и сайт начнет работать корректно.
- Проверьте подключение к сети Интернет. Браузер может не получать данные с сервера из-за нестабильного соединения или низкой скорости. Попробуйте перезагрузить роутер или отключите его на некоторое время от электросети.
Скачать
файл
- Попытайтесь зайти на другой сайт, чтобы убедиться, что проблема не в настройках вашего устройства. Если вы сможете зайти на иную площадку, значит, ошибка возникла со стороны владельца веб-ресурса. Вы сможете попасть на нужную страницу, когда администратор восстановит доступ.
- Почистите файлы cookies. Если при повторном входе на сайт по-прежнему отображается ошибка 502, попробуйте очистить кэш браузера. Возможно, доступ уже был восстановлен, но ваш обозреватель обращается к старой версии страницы из памяти.
- Попробуйте другой сервис. Если ошибка при открытии сайта возникает только на одном устройстве, возможно, проблема в настройках конкретной программы. Решить ее может помочь использование другого браузера.
- Отключите расширения и плагины. Причиной ошибки могут быть плагины и расширения (особенно для работы с прокси- и VPN-сервисами), которые блокируют доступ к некоторым сайтам. Попробуйте отключить их и снова зайти на страницу.
- Очистите кэш DNS. DNS-кэш – это своего рода база данных, которая временно хранит IP-адреса ранее посещенных сайтов с вашего компьютера, чтобы впоследствии они загружались быстрее. При смене DNS данные из памяти будут отправлять по старому пути, и в браузере появится код ошибки 502. После очистки кэша сервис будет обращаться уже к новому IP-адресу.
Ниже приведены инструкции для разных операционных систем:
- В Windows 10, чтобы избавиться от ошибки 502, комбинацией клавиш Win+R откройте командную строку, введите «cmd» и нажмите OK. В открывшемся окне наберите команду ipconfig /flushdns и нажмите Enter. Дождитесь оповещения об успешной очистке кэша.
- В Windows 7 в консоли введите команду ipconfig /flushdns и нажмите Enter. Затем выполните команды net stop dnscache и net start dnscache, чтобы перезапустить службу DNS-клиента.
- В macOS нажмите на иконку поиска в правом верхнем углу и напишите «Терминал», кликните по найденному приложению. В открывшемся окне введите команду sudo killall -HUP mDNSResponder.
- В Linux запустите терминал из основного меню или сочетанием клавиш Ctrl + Alt + T. Для Ubuntu – введите команду sudo service network-manager restart и нажмите Enter (иногда она работает и на других дистрибутивах). Для иных вариантов попробуйте sudosystem-resolve –flush-caches или sudo /etc/init.d/nscd restart.
В некоторых дистрибутивах может потребоваться запуск других команд.
- Измените DNS-сервер по умолчанию. Данное действие может повысить безопасность и скорость. Для этого в настройках роутера нужно указать адреса публичных DNS-серверов.
- Свяжитесь с администратором. Если у вас есть контакты администратора сайта, расскажите ему об ошибке, с которой столкнулись. Возможно, он еще не в курсе проблемы и, соответственно, пока не решает ее.
Рекомендации администратору по исправлению ошибки 502
В первую очередь необходимо проверить журнал ошибок
В WordPress он расположен в папке wp-content, имя файла debug.log. Если такого файла нет или он пустой, то нужно включить запись логов в конфигурационном файле wp-config.php.
Дарим скидку от 60%
на курсы от GeekBrains до 24 сентября
Уже через 9 месяцев сможете устроиться на работу с доходом от 150 000 рублей
Забронировать скидку
Если у вас VPS/VDS или выделенный сервер, нужно дополнительно посмотреть логи сервера. Это поможет определить:
- влияют ли обновления на сервере на возникновение ошибки 502;
- признаки DDoS-атаки (массовые однотипные запросы);
- подозрительную активность с некоторых IP-адресов;
- отсутствие соединения между вашими серверами Nginx, Apache и т. д.
По результатам проверки можно предпринимать действия для решения возникшей проблемы.
Использование команды top
Исправление ошибки 502 на виртуальном сервере можно начать с проверки командой top (на виртуальном хостинге такой вариант чаще всего недоступен).
Проверка может выявить следующие причины возникшей проблемы:
- Недостаточно памяти сервера. На это укажет аббревиатура OOM (out of memory) в результатах или же в параметре Mem – free (свободная память) будет слишком маленькое число.
- Если ошибка 502 по причине нехватки памяти возникает все чаще, вероятно, посещаемость площадки выросла, и вам нужно увеличить на сервере объем оперативной памяти или выбрать другой тариф.
- Недостаточно лимита php-cgi процессов для обработки запросов пользователей. Возможно, установлены слишком маленькие лимиты. Попробуйте их увеличить в конфигурационном файле httpd.conf.
Проверьте плагины в WordPress
Если ваш сайт создан на WordPress, некоторые плагины и темы могут влиять на работу сервера. Войдите в панель управления. Если вы пользуетесь услугой REG.Site, сделать это можно из личного кабинета. Перейдите во вкладку «Плагины» –«Установленные». Нажмите «Деактивировать» у того, который, по вашему мнению, повлиял на работу сайта.
Только до 25.09
Скачай подборку материалов, чтобы гарантированно найти работу в IT за 14 дней
Список документов:
ТОП-100 площадок для поиска работы от GeekBrains
20 профессий 2023 года, с доходом от 150 000 рублей
Чек-лист «Как успешно пройти собеседование»
Чтобы получить файл, укажите e-mail:
Введите e-mail, чтобы получить доступ к документам
Подтвердите, что вы не робот,
указав номер телефона:
Введите телефон, чтобы получить доступ к документам
Уже скачали 52300
Можно отключить сразу все плагины, чтобы убедиться, что один из них действительно мешает. И далее по очереди включать по одному, пока не обнаружите тот самый, по вине которого возникает ошибка.
Проверьте, как работают вспомогательные службы, например, MySQL и Memcached
Порой они могут быть причиной ошибки 502.
Попробуйте отключить анти-DDoS
Часто хостинги предлагают готовые инструменты, которые предупреждают DDoS-атаки, перенаправляя трафик посетителей на специальные серверы. Там DDoS-запросы отделяются от реальных, и вашему ресурсу передаются уже очищенные. Если в этой последовательности процессов происходит какой-то сбой, то возникает ошибка 502. Чтобы устранить проблему, попробуйте временно отключить анти-DDoS.
Увеличьте количество ресурсов
Нехватка мощности хостинга, на котором размещен сайт, может быть причиной ошибки 502. Особенно часто такое возникает при использовании виртуальных серверов. Если при работе сайта вы превышаете ограничения тарифного плана, хостинг разрывает соединение.
Читайте также
Обычно информацию об этом можно найти в логах. В этом случае нужно арендовать сервер с большим количеством процессоров и оперативной памяти.
Попросите помощи у коллег
Поищите решение проблемы в FAQ вашего провайдера или на Stack Overflow. Вероятнее всего, вы не первый, кто столкнулся с подобной ситуацией, и рабочий вариант исправления бага уже описан. Если же найденные в Интернете советы не окажутся полезными, вы можете создать свою тему на форуме или попросить помощи у более опытных коллег.
Свяжитесь со службой поддержки своего хостинг-провайдера и подробно опишите проблему и все действия, которые были предприняты.
Если и это не помогло, стоит обратиться за консультацией к специалисту
Он проанализирует проблему, выяснит причину возникновения ошибки и устранит ее.
Появление ошибки 502 Bad Gateway – нередкий случай. Справиться с ней могут как специалисты, так и пользователи сайта. Регулярная оптимизация веб-ресурсов положительно скажется на их работе и доступности.
When it comes to websites, there are a lot of different errors that can be downright frustrating and confusing. A few that come to mind are the white screen of death or the frightening error establishing a database connection.
But an even more popular one is the 502 bad gateway error. Why? Because this regularly happens around the entire web, not only to WordPress sites, but even popular services such as Gmail, Twitter, and Cloudflare.
Read more below about what causes this error and some solutions on how to quickly resolve it.
What is a 502 Bad Gateway Error?
The 502 Bad Gateway error specifically means that the server received an invalid response from an inbound server.
The Internet Engineering Task Force (IETF) defines the 502 Bad Gateway error as:
The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
Every time you visit a website your browser sends a request to a web server. The web server receives and processes the request, and then sends back the requested resources along with an HTTP header and HTTP status code. Typically an HTTP status code isn’t seen unless something goes wrong. It’s basically the servers way of notifying you that something has gone wrong, along with the code on how to diagnose it.
Error Code | 502 Bad Gateway Error |
Error Type | Server-side error |
Error Variations | “502 Bad Gateway” “Error 502” “HTTP Error 502 – Bad Gateway” “502 Service Temporarily Overloaded” “502 Proxy Error” A blank white screen “502 Server Error: The server encountered a temporary error and could not complete your request” “HTTP 502” Temporary Error (502) 502. That’s an error 502 bad gateway Cloudflare Bad Gateway: The proxy server received an invalid response from an upstream server |
Error Causes | Server overload Browser issues DNS issues Web host issues Firewall blocks Plugins and themes errors |
There are many different types of 500 status error codes (500, 501, 502, 503, 504, 508, 520, etc.) which all have slightly different meanings.
These indicate that the request was accepted, but the server prevented the fulfillment of the request.
Check Out Our Video Guide to Fixing Different Types of 500 Errors
What Causes the 502 Bad Gateway Error?
The most likely causes of the 502 Bad Gateway are:
- Server overload: the server ran out of resources and crashed, triggering an HTTP error 502. The possible reasons for this could be an unexpected spike in traffic or low memory.
- Browser problems: your browser version is outdated or maybe there are corrupted files in your browser cache.
- Firewall blocks: your firewall might be detecting false threats and blocking internet providers or IP addresses.
502 Bad Gateway Error Variations
Due to the various browsers, web servers, and operating systems, a 502 bad gateway error can present itself in a number of different ways. But they all have the same meaning. Below are just a couple of the many different variations you might see on the web:
- “502 Bad Gateway”
- “Error 502”
- “HTTP Error 502 – Bad Gateway”
- “502 Service Temporarily Overloaded”
- “502 Proxy Error”
- A blank white screen
- “502 Server Error: The server encountered a temporary error and could not complete your request”
- “HTTP 502”
- Temporary Error (502)
- 502. That’s an error
- 502 bad gateway Cloudflare
- Bad Gateway: The proxy server received an invalid response from an upstream server
Another variation you might see is a “502 server error.”
And here is yet another variation. “502 – Web server received an invalid response while acting as a gateway or proxy server. There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.”
Other services such as Twitter might even show a completely different message for a 502 Bad Gateway error, such as “Twitter is over capacity.” This definitely looks a little more user-friendly.
And here is a snapshot of how Google displays it. “502. That’s an error. The server encountered a temporary error and could not complete your request. Please try again in 30 seconds. That’s all we know.”
502 Errors Impact on SEO
Unlike 503 errors, which are used for WordPress maintenance mode and tell Google to check back at a later time, a 502 error can have a negative impact on SEO if not fixed right away. If your site is only down for say 10 minutes and it’s being crawled consistently a lot of times the crawler will simply get the page delivered from cache. Or Google might not even have a chance to re-crawl it before it’s back up. In this scenario, you’re completely fine.
However, if the site is down for an extended period of time, say 6+ hours, then Google might see the 502 error as a site level issue that needs to be addressed. This could impact your rankings. If you’re worried about repeat 502 errors you should figure out why they are happening to begin with. Some of the solutions below can help.
How to Fix the 502 Bad Gateway Error? 13 Methods
A 502 bad gateway error is typically a problem with the network/server, however, it can also be a client-side issue. So we’ll dive into a little of both. Check out these common ways to fix the 502 bad gateway error to get back up and running.
1. Try Reloading the Page
One of the easiest and first things you should try when encountering a 502 bad gateway error is to simply wait a minute or so and reload the page (F5 or Ctrl + F5). It could be that the host or server is simply overloaded and the site will come right back.
2. Check the Site Status
Another thing you can do is to paste the website into downforeveryoneorjustme.com. This website will tell you if the site is down or if it’s a problem on your side. There are also other tools that can help.
3. Try a Different Browser
You could try a different browser to rule that out as an issue. If you’re using Google Chrome, for example, try using Microsoft Edge.
In case the error goes away, it might be a good idea to delete and reinstall the browser you initially used.
4. Try in Incognito Mode
You can also access the site in Incognito mode. If the 502 bad gateway error doesn’t happen, the problem might be caused by a browser extension.
But how to identify the culprit extension? Try disabling them gradually, one after the other, checking if the website will open normally.
When this happens, you will have deleted the extension that was blocking your access.
5. Test on Another Device
If it looks like a problem on your end, you can try accessing the website on a different device.
Do the test: use your cell phone’s mobile data to access the page you want to see. If you succeed, restart your computer and other networking equipment, following the classic tip of unplugging your wireless router, waiting a moment, and plugging it back in.
That way you will understand if the error is related to your networking devices or something else.
6. Clear Your Browser Cache
Whenever you encounter issues like these it can be good to clear your browser cache. Below are instructions on how to do it in the various browsers:
- How to Force Refresh a Single Page for All Browsers
- How to Clear Browser Cache for Google Chrome
- How to Clear Browser Cache for Mozilla Firefox
- How to Clear Browser Cache for Safari
- How to Clear Browser Cache for Internet Explorer
- How to Clear Browser Cache for Microsoft Edge
- How to Clear Browser Cache for Opera
7. Check for DNS Issues
A 502 gateway error could also be because of a DNS issue, such as the domain is not resolving to the correct IP, or the DNS server is not responding. If you have just migrated your site to a new host, is it important to wait for things to fully propagate, which can take up to 24 hours in some cases. This depends upon the TTL value of your DNS records.
You can also try flushing your local DNS cache. This is similar to clearing your browser cache.
In Windows simply open up Command Prompt and enter the following:
ipconfig /flushdns
You should see a “Successfully flushed the DNS resolver Cache” if it worked.
For macOS users, you can enter the following in the terminal:
dscacheutil -flushcache
Note: There is no success message on Macs.
And lastly, you could temporarily change your DNS servers. By default, DNS servers are automatically assigned by your ISP. But you could try temporarily changing these to a public DNS server, such as Googles. In fact, some prefer to use Google’s public DNS long-term. If you have a premium DNS propagation usually is a lot faster.
8. Check With Your Host
The primary reason we typically see a 502 bad gateway error is due to an issue with the web host. Sometimes a query, script, or request will take too long and so it is canceled or killed by the server. A lot of hosts, especially shared hosts implement what they call a “kill script.” Basically what this does is it will terminate a request after a certain period of time so that it doesn’t take a site down or impact other users. If you do a Twitter search for “bad gateway” you can see thousands of tweets happening every day alerting their hosting company of the problem.
One reason you might want to consider moving to a host like Kinsta is that our platform runs in an isolated software container that contains all of the software resources required to run the site (Linux, NGINX, PHP, MySQL). This means that the software that runs each site is 100% private and is not shared, even between your own sites. This greatly reduces the chance of seeing a 502 bad gateway error. We aren’t running aggressive kill scripts like some shared hosts are. And even if one of your sites does happen to go down, it won’t impact your other sites.
Another reason you could see a 502 gateway error with your host is also due to the fact that the server is simply not reachable, either because it is down or there is no connectivity. In this case, it is recommended to check your host’s status page or open a support ticket.
9. Temporarily Disable CDN or Firewall
It could also be an issue with your content delivery network (CDN) or firewall. If you are using a 3rd-party CDN provider an easy way to troubleshoot this is to simply disable your CDN temporarily. For example, we are big fans of the free CDN enabler plugin. If you are using that, you can simply deactivate the plugin and then test your site.
Wp-admin not working? Simply log in to your site via SFTP and rename the plugin’s folder to cdn-enabler_old. This will temporarily disable the CDN connection. The same goes for WP Rocket or any other plugin you might have hooked up to your CDN.
This can also occur sometimes with providers that provide DDoS protection and mitigation or fully proxy services like Cloudflare, as they have extra firewalls in-between. We have noticed that this happens once in a while on the Cloudflare free plan. Unfortunately, since Cloudflare is a fully proxy service, there is no quick way to simply disable it.
However, before you go blaming Cloudflare, it is important to know that there are two different types of 502 bad gateway errors variations with Cloudflare as seen below:
502 Bad Gateway at Cloudflare (Variation 1)
If you see the following screen, this is actually a problem on Cloudflare’s end, in which case you should reach out to them for support. You can also check Cloudflare’s status page to see if they’re currently experiencing an outage.
502 Bad Gateway at Cloudflare (Variation 2)
If you see the following screen, this is a problem with your host.
GoDaddy Firewall
Here is another example with of an HTTP 502 error and GoDaddy’s firewall. The issue is actually with the origin server (the hosting provider) due to a timeout, not the firewall itself.
10. Check Your Plugins and Themes
A lot of times the reason for scripts and queries being canceled by the server is due to bad code on your site, possibly from a 3rd party plugin or theme. We have also seen a lot of misconfigured caching plugins generate 502 errors. A few ways you can troubleshoot this is by deactivating all your plugins. Remember, you won’t lose any data if you simply deactivate a plugin.
If you can still access your admin, a quick way to do this is to browse to “Plugins” and select “Deactivate” from the bulk actions menu. This will disable all of your plugins. If this fixes the issue you’ll need to find the culprit. Start activating them one by one, reloading the site after each activation. When you see the 502 gateway error return, you’ve found the misbehaving plugin. You can then reach out to the plugin developer for help or post a support ticket in the WordPress repository.
If you can’t access your admin you can FTP into your server and rename your plugins folder to something like plugins_old. Then check your site again. If it works, then you will need to test each plugin one by one. Rename your plugin folder back to “plugins” and then rename each plugin folder inside of if it, one by one, until you find it.
Always makes sure your plugins, themes, and WordPress core are up to date. And check to ensure you are running a supported version of PHP. You can always reach out to your host for assistance. We use Kinsta APM and other troubleshooting methods here at Kinsta to help clients narrow down what plugin, query, or script might be causing the error. You can also use your own custom New Relic key if you have your own license.
If it turns out to be an efficient query or bad code in a plugin, you might need to bring in a WordPress developer to fix the issue.
11. Check Logs
You should also take advantage of your error logs. If you are a Kinsta client, you can easily see errors in the log viewer in the MyKinsta dashboard. This can help you quickly narrow down the issue, especially if it’s resulting from a plugin on your site.
If your host doesn’t have a logging tool, you can also add the following code to your wp-config.php file to enable logging:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
If you need more help on how to enable WordPress debugging mode here is a full step by step tutorial.
The logs are typically located in the /wp-content directory. Others, like here at Kinsta might have a dedicated folder called “logs”.
You can also check the log files in Apache and NGINX, which are commonly located here:
- Apache: /var/log/apache2/error.log
- NGINX: /var/log/nginx/error.log
If you are a Kinsta client you can also take advantage of our analytics tool to get a breakdown of the total number of 502 errors and see how often and when they are occurring. This can help you troubleshoot if this is an ongoing issue, or perhaps something that has resolved itself.
12. Restart PHP
Finally, you can also try restarting PHP. If you’re a Kinsta client, you can easily restart PHP from the tools menu within the MyKinsta dashboard. If your host doesn’t provide this, you can always open up a support ticket and ask them restart PHP.
13. Check for PHP Timeout Issues
PHP timeouts occur if a single PHP process runs for longer than the max_execution_time
or max_input_time
set in the PHP configuration on your server. This is a common occurrence if you’re doing big WordPress imports. When this happens a 502 server error is usually displayed. If you run into a PHP timeout these values may need to be elevated.
You can check with your current host about what values are set on your server and if they can be increased. On the Kinsta platform, these values are set to 300 seconds (5 minutes) by default. The maximum PHP timeout values available on our platform are based on your current hosting plan.
Summary
As you can see there are quite a few things you can do to troubleshoot and fix a 502 gateway error on your site. Typically this is not on the client-side, but rather an issue with your host. Third-party plugins and themes with bad code or unoptimized queries are also things to watch out for.
Was there anything we missed? Perhaps you have another tip on troubleshooting 502 gateway errors. If so, let us know below in the comments.
FAQ
What Is a 502 Bad Gateway Error?
The 502 Bad Gateway error indicates that one server on the internet received an invalid response from another server. It’s a generic error alerting you that there’s something wrong with a website’s server communication.
What Causes the 502 Error?
The 502 bad gateway error is typically caused by issues related to the network/server, however, it can also be caused by client-side issues.
How Do You Fix the 502 Bad Gateway Error?
There are a number of things you can try when attempting to fix the 502 Bad Gateway Error:
- Try Reloading the Page
- Check the Site Status
- Try a Different Browser
- Try in Incognito Mode
- Test on Another Device
- Clear Your Browser Cache
- Check for DNS Issues
- Check With Your Host
- Temporarily Disable CDN or Firewall
- Check Your Plugins and Themes
- Check Logs
- Restart PHP
- Check for PHP Timeout Issues
Brian Jackson
Brian has a huge passion for WordPress, has been using it for over a decade, and even develops a couple of premium plugins. Brian enjoys blogging, movies, and hiking. Connect with Brian on Twitter.
-
LinkedIn
-
Twitter
Understand the HTTP 502 Bad Gateway error: What are the causes and how to fix them.
Table of Contents
- What is the 502 Bad Gateway error?
- Different 502 error messages
- 502 Bad Gateway causes
- How to fix the 502 Bad gateway error code
- 1 Verify your server is up and running
- 2 Verify your server is reachable
- Verify your server bypassing your proxy service
- Verify your server by disabling the proxy service
- Verify your server is reachable around the World
- 3 Verify your server load
- 4 Verify the resource limits of your hosting
- 5 Check the CDN or proxy service status
- 6 Inspect your server firewall
- 7 Inspect the DNS
- 8 Check your Database
- 9 Check your WordPress or application
- All HTTP Status Codes
What is the 502 Bad Gateway error?
The HTTP 502 Bad Gateway response status code indicates that your server is behind a proxy (e.g. a CDN, a Load Balancer, a Firewall, …), and it is not visible. For instance, your CDN or Firewall can’t reach your web server and your content can’t be served to the user.
Different 502 error messages
- “Error 502 Bad gateway”
- “Proxy Error. The proxy server received an invalid response from an upstream server.”
- “502 Bad Gateway Nginx”
- “HTTP 502”
- “502 Service Temporarily Overloaded”
- “502 Server Error: The server encountered a temporary error and could not complete your request”
- “502. That’s an error. The server encountered a temporary error and could not complete your request”
- “Temporary Error (502)”
The following sections show you the causes, and how to fix the error:
502 Bad Gateway causes
The 502 error means that the proxy service acting as Gateway has a problem getting the content from your server. This proxy service you have in front of your site server can be a CDN, a Load Balancer, a Firewall, etc.
Here you have a list of all the different causes:
- There is a network problem between your server and your proxy service.
- Your server is blocking access to the proxy service.
- Your server is down.
- Your server is up but can’t handle more connections.
- Some server requests return an error.
- There is an invalid or incorrect DNS zone.
How to fix the 502 Bad gateway error code
You can follow the next steps to find the cause and fix the 502 error:
1 Verify your server is up and running
This is the first step you have to verify. Login to your server console or panel and verify that all web services are running.
2 Verify your server is reachable
Temporarily disable the proxy service or skip it forcing your domain DNS zones. We describe below the two methods:
Verify your server bypassing your proxy service
You can bypass the proxy service by pointing your domain name directly to the IP of your server.
You can force the DNS zones, modifying the host file of your computer.
You have tools to help you like:
SwitchHosts for Mac OSX or
HostsFileEditor for Windows.
Verify your server by disabling the proxy service
As an alternative to verify if your server is reachable, you can temporarily disable your proxy service.
If you are using Cloudflare, you can easily disable it from the admin panel. Log in and in the right sidebar, find Quick Actions and enable “Development Mode”:
Verify your server is reachable around the World
If you can temporarily disable the proxy service, the next recommended checkpoint is to verify if this server is reachable across different networks.
We recommend you the Uptrends Website Uptime Test online tool:
This Uptrends tool checks your site from different country nodes. If some check fails, this will help you identify potential network problems.
3 Verify your server load
If your web server reaches its limit, it can’t answer any more requests, and the gateway delivers the status code 502 Bad Gateway. The reason could be an unexpectedly high interest in the site or even a DDoS attack. This means that an attacker is using a bot network to help overload the server capacity and provoke a system failure.
Your proxy service, CDN, or Load Balancer may be ready to handle high volumes of traffic, but that doesn’t mean your web server is. With WordPress websites, it is extremely easy to overload the server, since there are many pages with high processing time and that we cannot serve from cache.
The best solution in case of non-legit traffic is to be protected by a CDN or Firewall service capable of filtering traffic, and ready to deal with DoS and DDoS attacks.
At Wetopi, as WordPress specialists, we know how important it is to add strong measures of security.
We apply three techniques to filter traffic:Shared security heuristic learning,
Blacklisting from external sources and
Mitigation of DDoS attacks.
If your traffic is legit, the solutions are obvious:
- Add cache to your site.
- If a cache system is not enough, then add more resources to your server.
- If you cannot financially face the increase in resources, the final option is to lighten your website. If you work with WordPress, reduce the number of plugins to the essential minimum.
4 Verify the resource limits of your hosting
If your website is in a shared hosting, check that you’re not overstepping resource limits.
The establishment of limits is not something that you can find among the functionalities of a “shared hosting”. But keep in mind that to preserve coexistence between all the sites on a shared server, it is very common for the provider to set limits on processing time, on the number of “php workers” and on traffic.
One reason you might want to consider moving to a Hosting like Wetopi is that each WordPress installation runs on an isolated host that contains all of the software resources required to run the site (Linux, Nginx, Php-fpm, MySQL). This means that the software that runs each site is 100% private and is not shared, even between your own WordPress sites.
5 Check the CDN or proxy service status
This networking access problem could be a problem with your proxy service. Check the status service page of your proxy service.
This is a list of “Status Pages” of main providers of Load Balancing, CDN, and Security services:
- Cloudflare status page
- Sucuri status
- KeyCDN status
- StackPath status
- Google cloud services status
- Amazon Cloudfront status
6 Inspect your server firewall
If your web server has a local firewall: “iptables”, “Uncomplicated Firewall – UFU”, “CSF Firewall”, “Fail2ban”, “FireHOL”, … Then it could be this firewall that is blocking the access to your proxy service.
Inspect the firewall.
iptables
is blocking traffic from different IP addresses.
The best solution, in this case, is to add your proxy service IP addresses to the whitelist system of your firewall.
For instance, at Wetopi, we use and recommend Cloudflare as a CDN and security reverse proxy. To prevent “502 Bad Gateway” error problems, our server firewalls have the public list of Cloudflare’s IP addresses in the whitelist’s system.
7 Inspect the DNS
If you are in the process of publishing your domain or modifying it, the problem could be in the DNS
To fix the 502 error due to a DNS problem follow this checklist:
- If you have just migrated your site to a new host, is it important to wait for DNS zones to fully propagate, which can take up to 24 hours in some cases. This depends on the TTL value of your DNS records.
- The domain name is not resolving to the correct IP or it does not resolve to any IP. Verify your DNS zone definition according to the instructions provided by your proxy service: CDN, Load Balancer, Security Service, …
8 Check your Database
If you made it this far and none of the above methods work, chances are that the error is caused by an error in your web, or application in a specific page or URL request.
First, you have to check the database health:
- look for errors in log files
- repair and/or optimize tables and indexes.
9 Check your WordPress or application
If your database is ok, the final solution to fix the 502 error on a specific web page or URL is to debug your site.
If your site is running with WordPress, try this: disable all your plugins, if the problem disappears, then your 502 error is caused by a WordPress Plugin.
Do not break your production site!
Staging environments are the solution!
To clone a WordPress site with Wetopi is as easy as a simple click.
To find the plugin causing the problem, we recommend following this process:
- Disable all your plugins.
- Check the page that gives you the HTTP Error.
- If the page Works, then enable one plugin from the disabled list and jump to the previous step 2.
- If the page Fails, then this last enabled plugin could be the one causing the HTTP Error.
We are techies passionate about WordPress. With wetopi, a Managed WordPress Hosting, we want to minimize the friction that every professional faces when working and hosting WordPress projects.
Not a wetopi user?
Free full performance servers for your development and test.
No credit card required.
All HTTP Status Codes
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reported
226 IM Used
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
308 Permanent Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
418 I’m A Teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
444 Connection Closed Without Response
451 Unavailable For Legal Reasons
499 Client Closed Request