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



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

502 ошибка Bad Gateway может проявляться по-разному. К примеру, 502 – Service Temporarily Overloaded или HTTP Error 502 – Bad Gateway.

Что вызывает 502 ошибку сервера

Ошибка 502 говорит о том, что обратный прокси-сервер (допустим, Apache) для сервера источника (например, nginx) получает некорректный ответ от исходного веб-сервера.

Посмотрев внимательнее, мы обнаружили, что Apache работает в нем как прокси nginx. Веб-сервер перезагружал http-сервис почти каждый час. Наш опыт в устранении подобных ошибок показывает, что ошибка 502 Bad Gateway появляется по одной из следующих причин:

  1. Перегруженность сервера. Веб-сервер может падать из-за нехватки ресурсов (например, оперативной памяти), вызываемой избытком выполняемых процессов или агрессивными действиями пользователей;

  2. Частая перезагрузка веб-сервера. Такое случается при ошибках конфигурации, сбоях в модулях, любых атаках, избытке выполняемых процессов и приложений. В результате пользователь видит временную 502 ошибку;
  3. Плохой код сайта. Сайты с устаревшими приложениями или корявым кодом влияют на правильное функционирование сервера и ведут к периодическому возникновению 502 ошибки;
  4. Ошибки сети. Прочие ошибки конфигурации сети (проблемы с DNS, маршрутизация, блокировка файерволом, используемым на сервере, проблемы у провайдера) также становятся причиной появления 502 ошибки сервера;
  5. Время ожидания серверного программного обеспечения. 502 ошибка неизбежна при снижении скорости выполнения запросов в nginx, когда средство кэширования (например, Varnish Cache) уходит в таймаут. Сюда же относятся и медленные запросы.

Как исправить 502 серверную ошибку в nginx

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

Затем мы покопались в конфигурации сервера, и увидели, что там отсутствовал модуль mod_rpaf. Именно это и вызывало падение сервера:

Rpaf – это модуль Reverse proxy add forward, разработанный для серверов Apache. Он нужен в том случае, если вы задаете Nginx фронденд-сервером и хотите получить реальный IP серверных запросов.

Данный модуль не работал под Apache-2.4, поэтому мы немного его подправили. После перекомпиляции и перезагрузки Apache ошибки сегментации прекратились.

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

Вот несколько советов, как исправить ошибку 502 bad gateway:


  • Следите за тем, чтобы файлы сайта (плагины и темы) своевременно обновлялись и не устаревали;
  • Оптимизируйте и исправляйте медленные MySQL-запросы;
  • Проводите аудит серверного программного обеспечения и вовремя обновляйте модули;
  • Избегайте проблем с маршрутизацией и отслеживайте любые перегрузки/атаки на сервер.

Перевод статьи «HOW TO FIX «502 SERVER ERROR – BAD GATEWAY» IN WEB SERVERS» был подготовлен дружной командой проекта Сайтостроение от А до Я.

www.internet-technologies.ru

Что означает ошибка 502

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

Одновременно зашло слишком много пользователей

Известный конфуз “удачной” рекламной кампании заключается в том, что созданный информационный пиар привлекает посетителей настолько активно, что сайт падает под полученной нагрузкой.


Также, превышение лимита подключений может быть одним из признаков DDos-атаки хакеров, для намеренного отключения вашего портала.

Возникли проблемы на хостинге

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

Будет полезно уточнить у администрации хостинга, что за ошибка 502 bad gateway возникла на сайте, и не причастны ли к этому ваши “веб-соседи”

Плохо настроен сервер

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

Проблемы подключаемых модулей

Если ошибка сервера 502 возникает лишь при обращении к скриптам определённого расширения, например PHP, возможно причина состоит в неправильной работе именно этого модуля сервера.

Как исправить ошибку 502 BAD GATEWAY

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

  • Запустите анализ аппаратной производительности. Если в момент появления ошибки оперативная память стала использоваться на пределе, постарайтесь увеличить ее объем
  • Проверьте файлы конфигураций INI. Вполне возможно, что там просто стоят слишком низкие предельные лимиты — сервер мог обработать запрос, но файл конфигурации выставил запрет.

  • Оптимизируйте работу скриптов. Постарайтесь не делать лишних запросов, разделите сайт на FRONTEND и BACKEND, используйте качественно настроенные популярные связки, такие как nginx + Apache для отдачи статики.
  • Если вы явно диагностировали проблему не у себя, а у провайдера, задумайтесь о покупке выделенного сервера или смене хостинга.

semantica.in

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

502 Bad Gateway, что это значитошибка 502 bad gateway что значит

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

Как правило, такую ошибку отдают ресурсы в ответ на обращение в случае, если имеются проблемы с работой прокси, DNS или хостинг-сервера. Собственно, все ошибки серии 5ХХ означают, что трудности возникли на стороне сервера. Причём чаще всего надпись на белом экране появляется именно при повторном обращении к определённому ресурсу.


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

Причины возникновения502 Bad Gateway

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

Первой причиной появления такой ошибки становится низкая мощность сервера, к которому обращается запрос. Например, если он рассчитан на обработку 5 тысяч запросов в секунду, а ему отправляют от 7 до 10 тысяч обращений, сервер очень скоро отправить пользователям ошибку 502. Для решения проблемы в данном случае необходимо наращивать мощности сервера, это добавление памяти, которой недостаточно в текущем объёме и расширение канала. Особенно свойственно появление такой проблемы для серверов, организованных на базе домашних ПК, подобную нагрузку обычный компьютер не в состоянии выдержать, поэтому при малейшем её увеличении сервер падает.


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

Как бороться

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

Что может предпринять пользователь502 bad gateway nginx что это значит как исправить

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

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

  2. В случае если первый тест показал, что с доступом в сеть у пользователя все в порядке можно предпринять ещё одну меру. Опытные пользователи советуют почистить cookies. При желании пользователь может сделать это для конкретного сайта или удалить все данные.

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

  • Если вы пользуетесь браузером «Интернет Эксплорер», то нажмите значок шестерёнки в верхнем правом углу страницы и в разделе безопасность выберите пункт «Удалить журнал браузера». Откроется диалоговое окно, в котором пользователю предложат выбрать что именно он хочет удалить. Отметьте нужные пункты и нажмите «Удалить».
  • Для тех, кто предпочитает Яндекс-браузер инструкция, следующая. Нажмите на сэндвич из трёх горизонтальных линий, расположенный сразу после перечня открытых вкладок. Выберите дважды пункт «История». Тут можно отметить и удалить данные выборочно. Для полной очистки выберите в основном меню раздел «Дополнительно» и нажмите «Очистить историю».
  • Пользователи Google Chrome должны выбрать в главном меню раздел «История». Затем на открывшейся странице развернуть боковую панель и выбрать команду «Очистить историю».

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

Рекомендации для владельцев ресурса

Если ваш сайт часто выдаёт в ответ на запрос ошибку 502 Bad Gateway, то вот некоторые рекомендации, которые помогут справиться с проблемой.502 bad gateway nginx/1.10.1 что это значит

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

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

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

strana-it.ru

Ошибки передачи данных.

При запросе документов нередко происходят ошибки передачи данных. Что из них можно узнать? По коду полученного ответа сервера можно понять, на чьей стороне она возникла и ее причины.
На каждый запрос пользователя сервер отвечает попытокой передачи данных в определенной последовательности и формате. Например, HTTP-ответ (Response) имеет следующий формат:

Статусная строка
Заголовки ответа
Заголовки данных (может отсутствовать — зависит от типа запроса).
Пустая строка
Данные (может отсутствовать — зависит от типа запроса).


Статусная строка имеет вид:
протокол/версия —- код —- статус
Статус — текстовая строка, комментирующая код, предназначена для человека; программное обеспечение анализирует только числовое значение кода.
Примеры статусных строк: HTTP/1.1 200 OK или HTTP/1.1 304 Not Modified

Код ответа является трехзначным числом. Коды разделены по группам в зависимости от первой цифры:

1xx Промежуточные информационные сообщения (практически не используется).

2xx Успешная обработка запроса.
Примеры:

200 OK — наиболее общий ответ: запрос обработан, запрошенный документ передан клиенту (или только его заголовки — в случае запроса HEAD).

206 Partial Content — клиенту передана часть документа в соответствии с заголовком "Range:", имевшимся в запросе.
3xx Для получения документа требуются дополнительные действия со стороны клиента.
Примеры:

301 Moved Permanently — запрошенный документ перемещен. Новый URI документа возвращается в заголовке "Location:". В качестве данных возвращается краткий комментарий со ссылкой на новое расположение документа. В последующих запросах этого документа клиенту следует использовать новый URI. Как правило броузеры автоматически генерируют новый запрос с указанным URI при получении кода 301. Сервер конфигурируется для возврата ответов с кодом 301 при реструктуризации его пространства документов — с тем, чтобы клиенты, использующие старые ссылки, перенаправлялись к новому расположению документов, а не получали ошибку 404 Not Found.

302 Found — запрошенный документ временно перемещен. Новый URI документа возвращается в заголовке "Location:". В качестве данных возвращается краткий комментарий со ссылкой на новое расположение документа. В последующих запросах этого документа клиенту следует использовать старый URI.

304 Not Modified — документ был запрошен с помощью условного GET-запроса и условие не выполнено (например, документ не был модифицирован с момента, указанного в запросе в заголовке "If-Modified-Since:"). Возвращаются только статусная строка и заголовки ответа, заголовки данных (документа) и сам документ не возвращаются.

4xx Ошибка клиента.
Примеры:

400 Bad Request — ошибка в формате запроса.

401 Unauthorized — для доступа к ресурсу требуется аутентификация, но заголовок "Authorization:" либо отсутствует, либо содержит неприемлемые аутентификационные данные. Заголовок "WWW-Authenticate:" ответа в этом случае должен содержать информацию, необходимую для того, чтобы клиент определил, какая требуется аутентификация. Подробнее о процедуре аутентификации доступа к закрытым ресурсам см. ниже п. "Обработка запроса клиента".

403 Forbidden Pages -Доступ к этим страницам закрыт. Сервер понял запрос, но намеренно отказался его выполнять. Аутентификация в этом случае не поможет. Причина отказа может быть передана в качестве данных HTTP-ответа. Если сервер не желает раскрывать причину отказа, он может использовать вместо кода 403 код 404.

404 Not Found — запрошенный ресурс не найден. Это наиболее общий ответ в случае невозможности передать клиенту запрошенный документ; при этом не делается никаких предположений о том, постоянно или временно ресурс недоступен, а также о причине его недоступности. Удалите из URL все, что стоит за последней косой чертой. Если автор не включил страницу index.html, Вы увидите список страниц.

405 Method Not Allowed — в запросе использовался не разрешенный сервером метод (например, DELETE). Список разрешенных методов должен быть помещен в заголовке "Allow:" HTTP-ответа.

406 Not Acceptable — в заголовках "Accept…" клиент указал параметры перезентации документа, которые не могут быть выполнены сервером для данного документа (например, нет такой кодировки символов, какая указана в "Accept-Charset:").

410 Gone — аналогично 404 "Not Found", однако подразумевается, что документ существовал ранее, но умышленно удален навсегда (сделан недоступным). Полезно для временных презентаций, более не актуальных, для персональных страниц сотрудников, более не работающих в организации и т.п.

5xx Ошибка сервера.
Примеры:

500 Internal Server Error — при обработке запроса произошла ошибка в программном обеспечении сервера. Типичный случай — ошибка в CGI-скрипте.

501 Not Implemented — сервер не обладает функциональностью, требуемой для выполнения запроса. Например, метод, указанный в запросе, не известен серверу.

502 Bad Gateway — сервер, действующий в качестве прокси-сервера, получил ошибочный (неадекватный) ответ от сервера, которому он перенаправил запрос клиента.

503 Service Unavailable — сервер временно не в состоянии обработать запрос (перегружен или находится на техобслуживании [maintanance]). Если известно время, через которое сервер вернется в рабочее состояние, оно может быть указано в заголовке "Retry-After:". Заметим, что в случае невозможности обслуживания запросов сервер не обязан выдавать ответ с кодом 503, а может просто отказывать в установлении TCP-соединения. Попытайтесь еще раз, секунд через тридцать.

504 Gateway Timeout — сервер, действующий в качестве прокси-сервера, не получил за некоторое установленное время ответ от сервера, которому он перенаправил запрос клиента. Этот же код прокси-сервер должен возвращать, если произошел тайм-аут при опросе сервера DNS, однако некоторые существующие прокси-серверы возвращают при этом код 400 или 500. Заголовки, передаваемые вслед за статусной строкой, делятся на собственно заголовки ответа и на заголовки данных, передаваемых в ответе (если такие заголовки требуются). Каждый заголовок начинается с новой строки и состоит из ключевого слова, за которым следует двоеточие, и данных. Порядок следования заголовков не имеет значения.
(Можете посмотреть источник: http://athena.vvsu.ru/inetcourse/labs/wwwftp.html)

Вот еще некоторые варианты.

Host Unknown. Неизвестный хост.
Некоторые сайты переезжают, не оставляя новых адресов. Проверьте, есть ли данное имя домена на 4domains.com и попробуйте указанные рядом с ним цифровые адреса.
File Contains No Data . Файл не содержит данных.
Это сообщение означает, что страница существует, но в настоящее время пуста. Обратитесь к ней позднее: там могут появиться новые данные.
Too Many Connections —Try Again Later. Слишком много соединений—попробуйте еще раз.
Чтобы исправить эту ошибку, просто щелкайте по кнопке Refresh до тех пор, пока не найдется свободный канал и страница не загрузится.

А ВОТ ОРИГИНАЛ ;-))))

Status Code Definitions
RFC 2616 HTTP/1.1 June 1999

Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response.

Informational 1xx

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.

A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.

Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. (For example, if a proxy adds a "Expect: 100-continue" field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).)

100 Continue

The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.

101 Switching Protocols

The server understands and is willing to comply with the client’s request, via the Upgrade message header field (section 14.42), for a change in the application protocol being used on this connection. The server will switch protocols to those defined by the response’s Upgrade header field immediately after the empty line which terminates the 101 response.

The protocol SHOULD be switched only when it is advantageous to do so. For example, switching to a newer version of HTTP is advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features.

Successful 2xx

This class of status code indicates that the client’s request was successfully received, understood, and accepted.

200 OK

The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:

GET an entity corresponding to the requested resource is sent in the response;

HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;

POST an entity describing or containing the result of the action;

TRACE an entity containing the request message as received by the end server.

201 Created

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

202 Accepted

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.

203 Non-Authoritative Information

The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version. For example, including local annotation information about the resource might result in a superset of the metainformation known by the origin server. Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK).

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

205 Reset Content

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response MUST NOT include an entity.

206 Partial Content

The server has fulfilled the partial GET request for the resource. The request MUST have included a Range header field (section 14.35) indicating the desired range, and MAY have included an If-Range header field (section 14.27) to make the request conditional.

The response MUST include the following header fields:

— Either a Content-Range header field (section 14.16) indicating the range included with this response, or a multipart/byteranges Content-Type including Content-Range fields for each part. If a Content-Length header field is present in the response, its value MUST match the actual number of OCTETs transmitted in the message-body.

— Date

— ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request

— Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant

If the 206 response is the result of an If-Range request that used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. If the response is the result of an If-Range request that used a weak validator, the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers. Otherwise, the response MUST include all of the entity-headers that would have been returned with a 200 (OK) response to the same request.

A cache MUST NOT combine a 206 response with other previously cached content if the ETag or Last-Modified headers do not match exactly, see 13.5.4.

A cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial) responses.

Redirection 3xx

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.

Note: previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.

300 Multiple Choices

The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of

the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.

301 Moved Permanently

The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.

302 Found

The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

303 See Other

The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.

304 Not Modified

If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

The response MUST include the following header fields:

— Date, unless its omission is required by section 14.18.1

If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.

— ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request

— Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.

If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.

If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.

305 Use Proxy

The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.

Note: RFC 2068 was not clear that 305 was intended to redirect a single request, and to be generated by origin servers only. Not observing these limitations has significant security consequences.

306 (Unused)

The 306 status code was used in a previous version of the specification, is no longer used, and the code is reserved.

307 Temporary Redirect

The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s) , since many pre-HTTP/1.1 user agents do not understand the 307 status. Therefore, the note SHOULD contain the information necessary for a user to repeat the original request on the new URI.

If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Client Error 4xx

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

If the client is sending data, a server implementation using TCP SHOULD be careful to ensure that the client acknowledges receipt of the packet(s) containing the response, before the server closes the input connection. If the client continues sending data to the server after the close, the server’s TCP stack will send a reset packet to the client, which may erase the client’s unacknowledged input buffers before they can be read and interpreted by the HTTP application.

400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" [43].

402 Payment Required

This code is reserved for future use.

403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

404 Not Found

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

406 Not Acceptable

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of available entity characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

Note: HTTP/1.1 servers are allowed to return responses which are not acceptable according to the accept headers sent in the request. In some cases, this may even be preferable to sending a 406 response. User agents are encouraged to inspect the headers of an incoming response to determine if it is acceptable.

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

407 Proxy Authentication Required

This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. The proxy MUST return a Proxy-Authenticate header field (section 14.33) containing a challenge applicable to the proxy for the requested resource. The client MAY repeat the request with a suitable Proxy-Authorization header field (section 14.34). HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" [43].

408 Request Timeout

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough

information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

410 Gone

The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.

The 410 response is primarily intended to assist the task of web maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed. Such an event is common for limited-time, promotional services and for resources belonging to individuals no longer working at the server’s site. It is not necessary to mark all permanently unavailable resources as "gone" or to keep the mark for any length of time — that is left to the discretion of the server owner.

411 Length Required

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.

412 Precondition Failed

The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.

413 Request Entity Too Large

The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.

If the condition is temporary, the server SHOULD include a Retry- After header field to indicate that it is temporary and after what time the client MAY try again.

414 Request-URI Too Long

The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a URI "black hole" of redirection (e.g., a redirected URI prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit security holes present in some servers using fixed-length buffers for reading or manipulating the Request-URI.

415 Unsupported Media Type

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

416 Requested Range Not Satisfiable

A server SHOULD return a response with this status code if a request included a Range request-header field (section 14.35), and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field. (For byte-ranges, this means that the first- byte-pos of all of the byte-range-spec values were greater than the current length of the selected resource.)

When this status code is returned for a byte-range request, the response SHOULD include a Content-Range entity-header field specifying the current length of the selected resource (see section 14.16). This response MUST NOT use the multipart/byteranges content- type.

417 Expectation Failed

The expectation given in an Expect request-header field (see section 14.20) could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server.

Server Error 5xx

Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.

500 Internal Server Error

The server encountered an unexpected condition which prevented it from fulfilling the request.

501 Not Implemented

The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.

502 Bad Gateway

The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.

503 Service Unavailable

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

Note: The existence of the 503 status code does not imply that a server must use it when becoming overloaded. Some servers may wish to simply refuse the connection.

504 Gateway Timeout

The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.

Note: Note to implementors: some deployed proxies are known to return 400 or 500 when DNS lookups time out.

505 HTTP Version Not Supported

The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.

Отредактировано Lexx (Чт, 15 Май 2008 09:40:14)

forum.mybb.ru

Что означает ошибка 502?

Код ответа HTTP, который начинается с цифры “5” относится к ошибкам связанным с утратой связи между серверами. Точная причина появления в большинстве случаем находится на стороне сервера.

Получение ошибки 502 bad gateway error означает, что сервер-источник отправил неверный ответ другому серверу, который выступает как шлюз или прокси. Поскольку все запросы в веб перенаправляются через множество шлюзов, может быть очень сложно определить точное место, где возникли сложности. Однако, есть основные шаги для выявления, выполнив которые можно исправить ошибку.Ошибка 502 bad gateway - как она выглядит в браузере

Ошибка 502 bad gateway может также возникать в разных формах и видах. Вот несколько вариантов её появления:

Temporary Error (502)
Error 502
HTTP Error 502 Bad Gateway
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
502 Service Temporarily Overloaded
502 Bad Gateway Nginx

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

Так как ошибка 502 bad gateway обычно связана с проблемами на стороне сервера, она может возникать из-за неверной конфигурации или проблемы с клиентской стороны. Мы рассмотрим шаги поиска решения в обоих случаях. В то время, как некоторые решения ориентированны на WordPress, большинство из них могут быть применены к любому сайту. Давайте приступим к шагам поиска причины и решению ошибки 502:

1. Обновите страницу

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

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

Если ошибка осталась, существует вариант, что какой-то закэшированный элемент приводит к ней. Тогда очистка кэша браузера – это хороший подход в выявлении причин ошибки 502 bad gateway.

3. Попробуйте другой браузер

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

4. Очистите кэш DNS

Ошибка 502 может возникать ещё и по причине, связанной с DNS, такой как неверное значение IP-адреса в кэше. В таком случае, сброс DNS кэша – это ещё одно решение, которое вы можете испробовать. Здесь руководство о том, как очистить кэш DNS на Windows, Mac и Linux.

Вы также можете временно переключить свой DNS сервер по умолчанию на Google Public DNS.

5. Проверьте на другом устройстке

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

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

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

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

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

Все созданные записи будут отображаться в файле wp-contents/debug.log.Включение журнала ошибок WordPress

7. Проверьте плагины

Также важно проверить ваши плагины и расширения. Проблемы с плагинами кэширования могут приводить к возникновению ошибкы 502 bad gateway. Простой способ проверить, заключается ли проблема в плагине – это не на долго отключить их все. Для этого перейдите в каталог wp-content и переименуйте каталог plugins.Ошибка 502 - поиск причины - отключение всех плагинов WordPress

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

8. Проверьте сети CDN

Иной причиной ошибки 502 bad gateway могут быть сети CDN или службы предотвращения DDoS. Одной из замечательных иллюстраций может быть CloudFlare, где ошибка 502 bad gateway бывает в двух разных вариантах, в зависимости от причины.Ошибка 502 - первый вариант в CloudFlare

Эта страница указывает, что возникла проблема на стороне CloudFlare и для её устранения вам нужно обратиться в их службу поддержки. Или же, вы можете выбрать отключить CloudFlare, но имейте в виду, что обновление DNS может занять несколько часов.Ошибка 502 - второй вариант в CloudFlare

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

9. Свяжитесь со своим провайдером услуг хостинга

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

Выводы

В этом руководстве мы изучили, что такое ошибка 502 bad gateway и какие существуют подходы к её решению.

Если у вас есть дополнительные подсказки, уловки или решения, смело делитесь ими с нами в комментариях ниже!

www.hostinger.ru

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

ошибка 502

Выражение «ошибка 502 bad gateway» можно перевести как «неверный шлюз». Это будет означать, что браузер (обозреватель Интернета) на вашем компьютере при запросе какой-либо информации с веб-узла получил неприемлемый ответ от другого сервера (DNS или прокси-сервера). Об этом и сообщается пользователю при выводе на экране сообщения «502 ошибка».

Большинство интернет-пользователей неоднократно сталкивались с такой ошибкой, однако для некоторых это может быть впервые. Что же делать, когда сообщение «ошибка 502» появилось на экране вашего компьютера? В первую очередь необходимо проверить, есть ли вообще доступ к Интернету. Для этого следует набрать в браузере адрес другого сайта, который гарантированно должен работать в данный момент, поскольку, например, корпоративный доступ к Интернету осуществляется посредством прокси-сервера, а не сразу же через модем, подключенный на вашем компьютере или встроенный в него. Если в последнем случае ошибка более детально распознается, то при доступе в Интернет посредством локальной сети система не имеет возможности проверить ошибку. В связи с этим пользователю не остается ничего другого, как выяснять причины ее появления косвенными методами.

ошибка 502 bad gateway

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

Для этого вы можете сделать следующее:

  • для Internet Explorer версий 7+: в меню заходите в «Сервис», затем выбираете «Свойства обозревателя», жмете на кнопку «Удалить», а после этого на кнопку «Удалить cookies»;
  • для более ранних версий Internet Explorer: заходите в «меню Tools» , ищете «Internet option» и нажимаете «Delete cookies»;
  • для Fierefox: заходите в «Инструменты», ищете «Настройки», выбираете « Cookies» и кликаете на «Очистить cookies»;
  • для Opera: заходите в «Инструменты», выбираете «Удалить личные данные» и отмечаете галочками необходимые опции;
  • для Google Chrome: заходите в «Инструменты», нажимаете «История», кликаете на «Очистить историю», а затем на «Очистить файлы cookies».

502 ошибка

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

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

fb.ru


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.