bitlvl
RU

Коды состояния HTTP

Ищите по номеру или слову. Последний столбец — ситуация, которая обычно порождает код, а это именно то, что нужно, когда вы смотрите на него в логе. Таблица на английском языке.

 
 
КодИмяЗначениеКогда вы его видите
100Continue
Информационный
The server has received the headers; send the body.After Expect: 100-continue, before uploading a large body.
101Switching Protocols
Информационный
The server agrees to change protocol.WebSocket handshake.
102Processing
Информационный
WebDAV: request accepted, still working.
103Early Hints
Информационный
Preliminary headers, mainly Link: rel=preload, before the final response.CDNs and Cloudflare to start loading assets early.
200OK
Успех
The request succeeded.The normal case.
201Created
Успех
A new resource was created; Location header points to it.POST to a collection in a REST API.
202Accepted
Успех
Accepted for processing, not finished.Async jobs and queues.
203Non-Authoritative Information
Успех
Response modified by a proxy.Rare.
204No Content
Успех
Success with nothing to return.DELETE, PUT, beacon endpoints, preflight responses.
205Reset Content
Успех
Success; the client should reset the form.Rare.
206Partial Content
Успех
Only the requested byte range is returned.Video streaming, resumable downloads (Range header).
207Multi-Status
Успех
WebDAV: multiple status codes in an XML body.
226IM Used
Успех
Delta encoding applied.Rare.
300Multiple Choices
Перенаправление
Several representations are available.Rare.
301Moved Permanently
Перенаправление
The resource has a new permanent URL; the browser caches the redirect. Method may change to GET.http→https, old URLs, www canonicalisation. Transfers SEO ranking.
302Found
Перенаправление
Temporary redirect; method may change to GET.Post-login redirects, A/B tests. Not cached by default.
303See Other
Перенаправление
Redirect to a different resource with GET.After a POST (post/redirect/get pattern).
304Not Modified
Перенаправление
The cached copy is still valid; no body.Conditional requests with If-None-Match / If-Modified-Since.
307Temporary Redirect
Перенаправление
Like 302 but the method and body must not change.Redirecting a POST without turning it into a GET; HSTS internal redirects in Chrome.
308Permanent Redirect
Перенаправление
Like 301 but the method and body must not change.Permanent redirects of API endpoints.
400Bad Request
Ошибка клиента
The request is malformed; the server will not process it.Invalid JSON, bad parameters, oversized headers, invalid Host.
401Unauthorized
Ошибка клиента
Authentication is required or failed. The response should say how (WWW-Authenticate).Missing or expired token. (Should have been called Unauthenticated.)
402Payment Required
Ошибка клиента
Reserved; used by some APIs for quota or billing problems.Stripe, some SaaS APIs, Cloudflare for some plan limits.
403Forbidden
Ошибка клиента
Authenticated (or not) but not allowed.Permission denied, WAF block, directory listing disabled, Cloudflare challenges.
404Not Found
Ошибка клиента
No resource at this URL.Typos, deleted pages, wrong routes. Should return a helpful page.
405Method Not Allowed
Ошибка клиента
The URL exists but not for this method; Allow header lists the valid ones.POST to a static file, GET on a webhook endpoint.
406Not Acceptable
Ошибка клиента
No representation matches the Accept headers.Rare; strict content negotiation.
407Proxy Authentication Required
Ошибка клиента
Authenticate with the proxy first.Corporate proxies.
408Request Timeout
Ошибка клиента
The server gave up waiting for the request.Slow clients; browsers retry silently.
409Conflict
Ошибка клиента
The request conflicts with the current state.Duplicate create, version mismatch, edit collisions.
410Gone
Ошибка клиента
Permanently removed, and the server knows it.Tells search engines to drop the URL faster than 404.
411Length Required
Ошибка клиента
Content-Length header missing.Some servers for chunked uploads.
412Precondition Failed
Ошибка клиента
An If-* condition failed.Optimistic concurrency with ETags (If-Match).
413Content Too Large
Ошибка клиента
Body exceeds the limit.nginx client_max_body_size, upload limits.
414URI Too Long
Ошибка клиента
The URL exceeds the limit (typically 8 KB).Huge GET query strings; use POST.
415Unsupported Media Type
Ошибка клиента
The Content-Type is not supported.Sending form data where JSON is expected.
416Range Not Satisfiable
Ошибка клиента
The Range header is outside the file.Broken resumable downloads.
417Expectation Failed
Ошибка клиента
The Expect header cannot be met.Old proxies with Expect: 100-continue.
418I'm a teapot
Ошибка клиента
April Fools RFC 2324.Easter eggs; some sites use it to reject bots.
421Misdirected Request
Ошибка клиента
Sent to a server that cannot produce a response for this host.HTTP/2 connection reuse across hostnames with the wrong certificate.
422Unprocessable Content
Ошибка клиента
Syntactically valid but semantically wrong.Validation errors in REST APIs (Rails, Laravel, GitHub).
423Locked
Ошибка клиента
WebDAV: resource is locked.
424Failed Dependency
Ошибка клиента
WebDAV: a previous request failed.
425Too Early
Ошибка клиента
The server will not process a request that might be replayed (TLS 1.3 0-RTT).
426Upgrade Required
Ошибка клиента
Switch to a different protocol.Forcing TLS or HTTP/2.
428Precondition Required
Ошибка клиента
The request must be conditional.APIs enforcing If-Match to prevent lost updates.
429Too Many Requests
Ошибка клиента
Rate limit hit; Retry-After says when to try again.API throttling, login brute-force protection, Cloudflare rate limiting.
431Request Header Fields Too Large
Ошибка клиента
Headers exceed the limit.Huge cookies.
451Unavailable For Legal Reasons
Ошибка клиента
Blocked by a legal demand.Geo-blocking for GDPR, court orders.
500Internal Server Error
Ошибка сервера
The server hit an unexpected error.Uncaught exceptions, misconfiguration. Check the server logs, not the browser.
501Not Implemented
Ошибка сервера
The server does not support the method.Rare; PATCH on old servers.
502Bad Gateway
Ошибка сервера
A proxy got an invalid response from the upstream.App server crashed or not listening; nginx/HAProxy/Cloudflare in front of a dead backend.
503Service Unavailable
Ошибка сервера
Temporarily unable to handle the request.Maintenance, overload, all backends down. Send Retry-After.
504Gateway Timeout
Ошибка сервера
The upstream did not answer in time.Slow backend behind a proxy (proxy_read_timeout, Cloudflare’s 100 s limit).
505HTTP Version Not Supported
Ошибка сервера
The HTTP version is not supported.Rare.
507Insufficient Storage
Ошибка сервера
WebDAV: out of space.
508Loop Detected
Ошибка сервера
WebDAV: infinite loop.
510Not Extended
Ошибка сервера
Further extensions required.Rare.
511Network Authentication Required
Ошибка сервера
Log in to the network first.Captive portals in hotels and airports.
520Cloudflare: Unknown Error
Cloudflare
The origin returned something Cloudflare could not interpret (empty reply, invalid headers, > 16 KB headers).Origin resets the connection or sends garbage.
521Cloudflare: Web Server Is Down
Cloudflare
Cloudflare could not connect to the origin on the port.Origin firewall blocking Cloudflare IPs, web server stopped.
522Cloudflare: Connection Timed Out
Cloudflare
TCP handshake with the origin timed out.Origin overloaded or unreachable, wrong DNS IP.
523Cloudflare: Origin Is Unreachable
Cloudflare
No route to the origin.Wrong IP in DNS, origin network down.
524Cloudflare: A Timeout Occurred
Cloudflare
TCP connected but the origin did not send a response within 100 seconds.Slow scripts, long reports, big uploads; move the work async.
525Cloudflare: SSL Handshake Failed
Cloudflare
TLS handshake with the origin failed.Full (strict) mode without a valid origin certificate, cipher mismatch.
526Cloudflare: Invalid SSL Certificate
Cloudflare
Origin certificate not trusted (Full strict).Self-signed origin cert; use a Cloudflare Origin Certificate.
530Cloudflare: Origin DNS Error / 1xxx
Cloudflare
Returned with a 1xxx error code in the body.Tunnel down, DNS error, bans.

Результаты и сообщения этого инструмента выводятся на английском языке.

Пять классов

1xx информационные, редко встречаются вне смены протокола. 2xx успех. 3xx перенаправление: клиент должен искать в другом месте. 4xx клиент сделал что-то не так (или ему не разрешено). 5xx сервер дал сбой. Браузер или клиент, встретив неизвестный код, трактует его как x00 своего класса, поэтому новые коды деградируют плавно.

Пары, которые путают

  • 301 vs 302 vs 307/308: 301 и 308 постоянные (кешируются, и поисковики переносят ранжирование); 302 и 307 временные. Варианты 7/8 запрещают менять метод, поэтому POST остаётся POST; 301/302 позволяют браузеру превратить его в GET. Используйте 308 для постоянных переездов API, 301 для веб-страниц, 303 после POST формы.
  • 401 vs 403: 401 означает «кто вы?» (учётные данные отсутствуют или неверны; повторите с аутентификацией). 403 означает «я знаю, кто вы, и ответ — нет». Возвращать 404 вместо 403 допустимо, когда вы не хотите раскрывать, что ресурс существует.
  • 502 vs 503 vs 504: все приходят от прокси перед вашим приложением. 502: бэкенд ответил мусором или закрыл соединение (упал, неверный порт). 503: ничего недоступно (обслуживание, все бэкенды лежат, перегрузка). 504: бэкенд отвечал слишком долго. Коды 52x от Cloudflare уточняют их дальше.
  • 400 vs 422: 400 для запроса, который сервер вообще не может разобрать; 422 для разобранного, но отклонённого при валидации. Многие API используют 400 для обоих случаев.

Cloudflare 52x

Cloudflare добавляет собственные коды для проблем между своим edge и вашим origin-сервером. 521 означает, что не удалось открыть TCP-соединение (файрвол, сервер лежит), 522 — соединение превысило тайм-аут (неверный IP, перегрузка), 524 — соединение установлено, но origin не ответил за 100 секунд, 525/526 — проблемы TLS с сертификатом origin (переключитесь на Full strict с Origin Certificate или на Flexible). Они всегда указывают на ваш сервер или путь к нему, никогда на посетителя.

Вопросы

В чём разница между 404 и 410?

404 говорит, что здесь сейчас ничего нет; 410 — что здесь было и удалено намеренно. Поисковики быстрее выбрасывают URL с 410. Используйте 410 для удалённого контента, который вы не будете восстанавливать.

Должен ли API возвращать 200 с ошибкой в теле?

Нет. Клиенты, прокси, кеши и мониторинг ориентируются на код состояния. Используйте 4xx для ошибок клиента и 5xx для сбоев сервера, с деталями в теле (RFC 9457 problem+json — стандартная форма).

Почему я получаю 502 от nginx?

nginx не смог получить корректный ответ от upstream: приложение не запущено, слушает другой порт или сокет, упало посреди запроса или прислало заголовки, которые nginx отверг. Смотрите логи приложения и error log nginx, а не браузер.

Что означает 429 и что мне делать?

Слишком много запросов: вы упёрлись в лимит частоты. Подождите время из заголовка Retry-After, затем повторите с backoff. Для API распределите вызовы во времени или запросите большую квоту.