Http error 303

From Wikipedia, the free encyclopedia

From Wikipedia, the free encyclopedia

The HTTP response status code 303 See Other is a way to redirect web applications to a new URI, particularly after a HTTP POST has been performed, since RFC 2616 (HTTP 1.1).

According to RFC 7231, which obsoletes RFC 2616, «A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred by the server over HTTP. However, the Location field value refers to a resource that is descriptive of the target resource, such that making a retrieval request on that other resource might result in a representation that is useful to recipients without implying that it represents the original target resource.»

This status code should be used with the location header, as described below. If a server responds to a POST or other non-idempotent request with a 303 See Other response and a value for the location header, the client is expected to obtain the resource mentioned in the location header using the GET method; to trigger a request to the target resource using the same method, the server is expected to provide a 307 Temporary Redirect response.

303 See Other has been proposed as one way of responding to a request for a URI that identifies a real-world object according to Semantic Web theory (the other being the use of hash URIs).[1] For example, if http://www.example.com/id/alice identifies a person, Alice, then it would be inappropriate for a server to respond to a GET request with 200 OK, as the server could not deliver Alice herself. Instead the server would issue a 303 See Other response which redirected to a separate URI providing a description of the person Alice.

303 See Other can be used for other purposes. For example, when building a RESTful web API that needs to return to the caller immediately but continue executing asynchronously (such as a long-lived image conversion), the web API can provide a status check URI that allows the original client who requested the conversion to check on the conversion’s status. This status check web API should return 303 See Other to the caller when the task is complete, along with a URI from which to retrieve the result in the Location HTTP header field.[2]

Example[edit]

Client request:

POST / HTTP/1.1
Host: www.example.com

Server response:

HTTP/1.1 303 See Other
Location: http://example.org/other

See also[edit]

  • RFC 1945 (HTTP 1.0)
  • RFC 7231 (HTTP 1.1)
  • Hypertext Transfer Protocol
  • List of HTTP status codes
  • Post/Redirect/Get
  • HTTP 301 (Permanent redirect)

References[edit]

  1. ^ «Cool URIs for the Semantic Web: Hash URIs». W3C Interest Group Note. 2008-12-03.
  2. ^ Allamaraju, Subbu; Allamaraju, Subrahmanyam (March 2010). RESTful Web Services Cookbook. O’Reilly Media. ISBN 9780596801687.
part of Hypertext Transfer Protocol — HTTP/1.1
RFC 2616 Fielding, et al.

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

10.1 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).)

10.1.1 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.

10.1.2 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.

10.2 Successful 2xx

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

10.2.1 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.

10.2.2 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.

10.2.3 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.

10.2.4 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).

10.2.5 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.

10.2.6 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.

10.2.7 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.

10.3 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.

10.3.1 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.

10.3.2 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.

10.3.3 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.

10.3.4 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.

10.3.5 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.

10.3.6 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.

10.3.7 306 (Unused)

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

10.3.8 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.

10.4 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.

10.4.1 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.

10.4.2 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].

10.4.3 402 Payment Required

This code is reserved for future use.

10.4.4 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.

10.4.5 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.

10.4.6 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.

10.4.7 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.

10.4.8 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].

10.4.9 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.

10.4.10 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.

10.4.11 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.

10.4.12 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.

10.4.13 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.

10.4.14 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.

10.4.15 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.

10.4.16 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.

10.4.17 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.

10.4.18 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.

10.5 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.

10.5.1 500 Internal Server Error

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

10.5.2 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.

10.5.3 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.

10.5.4 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.

10.5.5 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.

10.5.6 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.

Привет, читатель блога ZametkiNaPolyah.ru! Продолжим знакомиться с протоколом HTTP в рубрике серверы и протоколы и ее разделе HTTP протокол.  Данная публикация будет о HTTP кодах состояния перенаправления. К HTTP кодам перенаправления относятся следующие коды: 300, 301, 302, 303, 304, 305, 306, 307. Напомню, что коды перенаправления говорят клиенту о том, что для успешного завершения запроса необходимо выполнить какое-то действие. Обычно браузеры выполняют такие действия без вмешательства пользователя. В данной записи мы рассмотрим сперва все HTTP коды перенаправления, а затем рассмотрим каждый код в отдельности более подробно.

HTTP коды состояния перенаправления: 300, 301, 302, 303, 304, 305, 306, 307

HTTP коды состояния перенаправления: 300, 301, 302, 303, 304, 305, 306, 307

Общая информации о HTTP кодах перенаправления

Содержание статьи:

  • Общая информации о HTTP кодах перенаправления
  • HTTP код состояния 300: множественный выбор. HTTP код состояния 301: постоянно перенесен. HTTP код состояния 302: временно перемещен.
  • HTTP код состояния 303: смотреть другой ресурс. HTTP код состояния 304: ресурс не модифицирован. HTTP код состояния 305: использовать прокси сервер. HTTP код состояния 307: временное перенаправление

Если вы хотите узнать всё про протокол HTTP, обратитесь к навигации по рубрике HTTP протокол.  Да, эти коды состояния, как раз и есть тот самый Redirect 301 или склейка доменов, глупое выражение: Redirect 301 – склейка домена. Автор тоже этим грешил, автор каится и обещает исправиться. Все дело в том, что 301 – это всего лишь, код, который означает, что произошло перенаправление, а вот за склейку доменов отвечает HTTP сервер и его конфигурации, поэтому крайне неправильно говорить этот ваш редирект 301.

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

Для удобства давайте сведем все HTTP коды состояния перенаправления в единую таблицу и дадим им краткое описание.

HTTP ответ Описание кода состояния перенаправления
300 Multiple Choices HTTP код перенаправления 300: множественный выбор
HTTP код состояния 300 говорит клиенту о том, что запрошенный ресурс имеет несколько представлений и клиент в праве выбрать одно из предлагаемых представлений.  Действует ограничение в пять адресов максимум.
301 Moved Permanently HTTP код перенаправления 301: постоянно перемещен
HTTP код состояния 301 говорит клиенту о том, что запрашиваемая страница была перенесена на новый адрес, обычно браузер автоматически переходит по новому адресу.
302 Found HTTP код перенаправления 302: временно перемещен
HTTP код состояния 302 говорит клиенту о том, что запрашиваемый ресурс был временно перемещен на новый адрес.
303 See Other HTTP код перенаправления 303: смотри другой
HTTP код состояния 303 говорит клиенту о том, что ответ на запрос может быть найден по другому URI (про URI в HTTP найдешь информацию здесь), новый запрос следует выполнять методом GET (про HTTP методы смотри здесь).
304 Not Modified HTTP код перенаправления 304: не модифицирован
HTTP код состояния 304 говорит клиенту о том, что сервер выполнил условный GET запрос, но документ никак не изменился.
305 Use Proxy HTTP код перенаправления 305: используй прокси
HTTP код состояния 304 говорит клиенту о том, что запрошенный URL должен быть доступен через прокси, который указан в поле заголовка Location.
306 Unused HTTP код перенаправления 306: зарезервировано
Код состояния 306 использовался в прошлой версии HTTP протокола, на данный момент он не используется, но зарезервирован стандартом HTTP.
307 Temporary Redirect HTTP код перенаправления 307: временно перемещен
HTTP код состояния 307 говорит клиенту о том, что запрашиваемая страница временно переехала на новый адрес

Давайте более подробно поговорим про каждый из кодов состояний HTTP сервера класса перенаправления.

HTTP код состояния 300: множественный выбор. HTTP код состояния 301: постоянно перенесен. HTTP код состояния 302: временно перемещен.

HTTP код состояния 300 или код множественного выбора говорит о том, что клиент может выбрать несколько доступных представлений ресурса, но не более пяти. Каждое представление ресурса имеет свое уникальное месторасположения на сервере. Формат, в котором клиент будет получать HTTP объект определяется медиа типом данных (читай про типы данных в HTTP по этой ссылке), указанным в поле заголовка Content-Type. Иногда выбор выполняется автоматически браузером без участия пользователя, но стандарт HTTP протокола не дает никаких критериев, по которым должен происходить автоматический выбор, а так же не имеет никаких требований. Ответы HTTP сервера с кодом состояния 300 по умолчанию являются кэшируемыми, если в заголовках не указано иного.

HTTP код состояния 301 или код состояния постоянного переноса. Код состояния 301 сообщает браузеру о том, что для ресурса, к которому он обратился, назначен новый URI, и все обращения к этому ресурсу следует выполнять по новому URI, указанному в ответе HTTP сервера. Ответы сервера с кодом 301 являются кэшируемыми. В тех случаях, когда клиент использовал HTTP запрос с методом отличным от GET или HEAD, браузер спрашивает у пользователя, что делать дальше: переходить по новому URI или не надо.

HTTP код состояния 302 или код временного перемещения ресурса. Код состояния 302 говорит о том, что на данный момент ресурс временно доступен по другому URI и сообщает новый URI ресурса. Кэшируемость ответов сервера с кодом 302 зависит только от значений полей заголовка Cache-Control или Expires. В тех случаях, когда клиент использовал запрос с методом отличным от GET или HEAD, браузер спрашивает у пользователя, что делать дальше: переходить по новому URI или не надо.

HTTP код состояния 303: смотреть другой ресурс. HTTP код состояния 304: ресурс не модифицирован. HTTP код состояния 305: использовать прокси сервер. HTTP код состояния 307: временное перенаправление

HTTP код состояния 303 или код состояния смотреть другой ресурс. Если клиент получает ответ с кодом 303, то это означает, что ответ на его запрос может быть найден по другому URI и его можно запросить при помощи метода GET. Чаще всего ответы с кодом состояния 303 используются, чтобы вывести информацию из формы. Ответы сервера с кодом 303 не кэшируются.

HTTP код состояния 304 или код состояния ресурс не модифицирован. Клиент получает ответ от HTTP сервера с кодом 304 в том случае, когда посылался запрос с условным методом GET, но никаких изменений в документе не произошло. При этом HTTP сообщение от сервера не должно содержать тела. Ответ сервера всегда содержит следующие поля заголовков:

  • Date;
  • ETag или Content-Location;
  • Expires, Cache-Control или

Ответы сервера с кодом 304 всегда завершаются пустой строкой после полей заголовка.

HTTP код состояния 305. Код состояния 305 говорит браузеру о том, что ему нужно обратиться к ресурсу, используя прокси-сервер. Прокси-сервер в сообщениях с кодом состояния 305 указывается в поле Location. При этом HTTP сервер ожидает, что клиент повторит запрос, но уже через прокси сервер и даже при необходимости пройдет аутентификацию на прокси сервере.

HTTP код состояния 306 использовался в старых версиях протокола HTTP, но теперь является просто зарезервированным.

HTTP код состояния 307 аналогичен коду состояния 302.

Настраивая HTTP сервер не забывайте про особенности HTTP соединения и помните, что код состояния — это параметр HTTP.  Мы рассмотрели коды перенаправления HTTP, давайте перейдем к кодам ошибок клиента. В HTTP есть еще: информационные коды, успешные коды, коды ошибок клиента и коды ошибок сервера. А если тебе нужна информацию обо всех кодах состояния, обратись к справочнику HTTP кодов состояния, в котором есть полное описание всех кодов.

The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request.

A user agent can perform a retrieval request targeting that URI (a GET or HEAD request if using HTTP), which might also be redirected, and present the eventual result as an answer to the original request. Note that the new URI in the Location header field is not considered equivalent to the effective request URI.

This status code is applicable to any HTTP method. It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource, since doing so provides the information corresponding to the POST response in a form that can be separately identified, bookmarked, and cached, independent of the original request.

A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred by the server over HTTP. However, the Location field value refers to a resource that is descriptive of the target resource, such that making a retrieval request on that other resource might result in a representation that is useful to recipients without implying that it represents the original target resource. Note that answers to the questions of what can be represented, what representations are adequate, and what might be a useful description are outside the scope of HTTP.

Except for responses to a HEAD request, the representation of a 303 response ought to contain a short hypertext note with a hyperlink to the same URI reference provided in the Location header field.


  • Source: RFC7321 Section 6.4.4

303 CODE REFERENCES

Rails HTTP Status Symbol :see_other

Go HTTP Status Constant http.StatusSeeOther

Symfony HTTP Status Constant Response::HTTP_SEE_OTHER

Python2 HTTP Status Constant httplib.SEE_OTHER

Python3+ HTTP Status Constant http.client.SEE_OTHER

Python3.5+ HTTP Status Constant http.HTTPStatus.SEE_OTHER

Additional resources

  • Learn about web development
  • Learn about SEO
  • Web development services from WebFX
  • SEO services from WebFX
  • MDN Web Docs
  • W3Schools

Return to List of HTTP Status Codes

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result. RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP defines these standard status codes that can be used to convey the results of a client’s request. The status codes are divided into five categories.

  • 1xx: Informational – Communicates transfer protocol-level information.
  • 2xx: Success – Indicates that the client’s request was accepted successfully.
  • 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.
  • 4xx: Client Error – This category of error status codes points the finger at clients.
  • 5xx: Server Error – The server takes responsibility for these error status codes.

1xx Status Codes [Informational]

Status Code

Description

100 Continue

An interim response. Indicates to 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.

101 Switching Protocol

Sent in response to an Upgrade request header from the client, and indicates the protocol the server is switching to.

102 Processing (WebDAV)

Indicates that the server has received and is processing the request, but no response is available yet.

103 Early Hints

Primarily intended to be used with the Link header. It suggests the user agent start preloading the resources while the server prepares a final response.

2xx Status Codes [Success]

Status Code

Description

200 OK

Indicates that the request has succeeded.

201 Created

Indicates that the request has succeeded and a new resource has been created as a result.

202 Accepted

Indicates that the request has been received but not completed yet. It is typically used in log running requests and batch processing.

203 Non-Authoritative Information

Indicates that 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.

204 No Content

The server has fulfilled the request but does not need to return a response body. The server may return the updated meta information.

205 Reset Content

Indicates the client to reset the document which sent this request.

206 Partial Content

It is used when the Range header is sent from the client to request only part of a resource.

207 Multi-Status (WebDAV)

An indicator to a client that multiple operations happened, and that the status for each operation can be found in the body of the response.

208 Already Reported (WebDAV)

Allows a client to tell the server that the same resource (with the same binding) was mentioned earlier. It never appears as a true HTTP response code in the status line, and only appears in bodies.

226 IM Used

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.

3xx Status Codes [Redirection]

Status Code

Description

300 Multiple Choices

The request has more than one possible response. The user-agent or user should choose one of them.

301 Moved Permanently

The URL of the requested resource has been changed permanently. The new URL is given by the Location header field in the response. This response is cacheable unless indicated otherwise.

302 Found

The URL of the requested resource has been changed temporarily. The new URL is given by the Location field in the response. This response is only cacheable if indicated by a Cache-Control or Expires header field.

303 See Other

The response can be found under a different URI and SHOULD be retrieved using a GET method on that resource.

304 Not Modified

Indicates the client that the response has not been modified, so the client can continue to use the same cached version of the response.

305 Use Proxy (Deprecated)

Indicates that a requested response must be accessed by a proxy.

306 (Unused)

It is a reserved status code and is not used anymore.

307 Temporary Redirect

Indicates the client to get the requested resource at another URI with same method that was used in the prior request. It is similar to 302 Found with one exception that the same HTTP method will be used that was used in the prior request.

308 Permanent Redirect (experimental)

Indicates that the resource is now permanently located at another URI, specified by the Location header. It is similar to 301 Moved Permanently with one exception that the same HTTP method will be used that was used in the prior request.

4xx Status Codes (Client Error)

Status Code

Description

400 Bad Request

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

401 Unauthorized

Indicates that the request requires user authentication information. The client MAY repeat the request with a suitable Authorization header field

402 Payment Required (Experimental)

Reserved for future use. It is aimed for using in the digital payment systems.

403 Forbidden

Unauthorized request. The client does not have access rights to the content. Unlike 401, the client’s identity is known to the server.

404 Not Found

The server can not find the requested resource.

405 Method Not Allowed

The request HTTP method is known by the server but has been disabled and cannot be used for that resource.

406 Not Acceptable

The server doesn’t find any content that conforms to the criteria given by the user agent in the Accept header sent in the request.

407 Proxy Authentication Required

Indicates that the client must first authenticate itself with the proxy.

408 Request Timeout

Indicates that the server did not receive a complete request from the client within the server’s allotted timeout period.

409 Conflict

The request could not be completed due to a conflict with the current state of the resource.

410 Gone

The requested resource is no longer available at the server.

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.

412 Precondition Failed

The client has indicated preconditions in its headers which the server does not meet.

413 Request Entity Too Large

Request entity is larger than limits defined by server.

414 Request-URI Too Long

The URI requested by the client is longer than the server can interpret.

415 Unsupported Media Type

The media-type in Content-type of the request is not supported by the server.

416 Requested Range Not Satisfiable

The range specified by the Range header field in the request can’t be fulfilled.

417 Expectation Failed

The expectation indicated by the Expect request header field can’t be met by the server.

418 I’m a teapot (RFC 2324)

It was defined as April’s lool joke and is not expected to be implemented by actual HTTP servers. (RFC 2324)

420 Enhance Your Calm (Twitter)

Returned by the Twitter Search and Trends API when the client is being rate limited.

422 Unprocessable Entity (WebDAV)

The server understands the content type and syntax of the request entity, but still server is unable to process the request for some reason.

423 Locked (WebDAV)

The resource that is being accessed is locked.

424 Failed Dependency (WebDAV)

The request failed due to failure of a previous request.

425 Too Early (WebDAV)

Indicates that the server is unwilling to risk processing a request that might be replayed.

426 Upgrade Required

The server refuses to perform the request. The server will process the request after the client upgrades to a different protocol.

428 Precondition Required

The origin server requires the request to be conditional.

429 Too Many Requests

The user has sent too many requests in a given amount of time (“rate limiting”).

431 Request Header Fields Too Large

The server is unwilling to process the request because its header fields are too large.

444 No Response (Nginx)

The Nginx server returns no information to the client and closes the connection.

449 Retry With (Microsoft)

The request should be retried after performing the appropriate action.

450 Blocked by Windows Parental Controls (Microsoft)

Windows Parental Controls are turned on and are blocking access to the given webpage.

451 Unavailable For Legal Reasons

The user-agent requested a resource that cannot legally be provided.

499 Client Closed Request (Nginx)

The connection is closed by the client while HTTP server is processing its request, making the server unable to send the HTTP header back.

5xx Status Codes (Server Error)

Status Code

Description

500 Internal Server Error

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

501 Not Implemented

The HTTP method is not supported by the server and cannot be handled.

502 Bad Gateway

The server got an invalid response while working as a gateway to get the response needed to handle the request.

503 Service Unavailable

The server is not ready to handle the request.

504 Gateway Timeout

The server is acting as a gateway and cannot get a response in time for a request.

505 HTTP Version Not Supported (Experimental)

The HTTP version used in the request is not supported by the server.

506 Variant Also Negotiates (Experimental)

Indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper endpoint in the negotiation process.

507 Insufficient Storage (WebDAV)

The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.

508 Loop Detected (WebDAV)

The server detected an infinite loop while processing the request.

510 Not Extended

Further extensions to the request are required for the server to fulfill it.

511 Network Authentication Required

Indicates that the client needs to authenticate to gain network access.

6. REST Specific HTTP Status Codes

200 (OK)

It indicates that the REST API successfully carried out whatever action the client requested and that no more specific code in the 2xx series is appropriate.

Unlike the 204 status code, a 200 response should include a response body. 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)

A REST API responds with the 201 status code whenever a resource is created inside a collection. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.

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 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 a 202 (Accepted) response instead.

202 (Accepted)

A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occurs.

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 (job queue location) or some estimate of when the user can expect the request to be fulfilled.

204 (No Content)

The 204 status code is usually sent out in response to a PUT, POST, or DELETE request when the REST API declines to send back any status message or representation in the response message’s body.

An API may also send 204 in conjunction with a GET request to indicate that the requested resource exists, but has no state representation to include in the body.

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. However, any new or updated metainformation SHOULD be applied to the document currently in the user agent’s dynamic view.

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

301 (Moved Permanently)

The 301 status code indicates that the REST API’s resource model has been significantly redesigned, and a new permanent URI has been assigned to the client’s requested resource. The REST API should specify the new URI in the response’s Location header, and all future requests should be directed to the given URI.

You will hardly use this response code in your API as you can always use the API versioning for the new API while retaining the old one.

302 (Found)

The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide a URL in the Location header field. The user agent (e.g., a web browser) is invited by a response with this code to make a second. Otherwise identical, request to the new URL specified in the location field.

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g., POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. 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)

A 303 response indicates that a controller resource has finished its work, but instead of sending a potentially unwanted response body, it sends the client the URI of a response resource. The response can be the URI of the temporary status message, or the URI to some already existing, more permanent, resource.

Generally speaking, the 303 status code allows a REST API to send a reference to a resource without forcing the client to download its state. Instead, the client may send a GET request to the value of the Location header.

The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

304 (Not Modified)

This status code is similar to 204 (“No Content”) in that the response body must be empty. The critical distinction is that 204 is used when there is nothing to send in the body, whereas 304 is used when the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.

In such a case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.

Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.

307 (Temporary Redirect)

A 307 response indicates that the REST API is not going to process the client’s request. Instead, the client should resubmit the request to the URI specified by the response message’s Location header. However, future requests should still use the original URI.

A REST API can use this status code to assign a temporary URI to the client’s requested resource. For example, a 307 response can be used to shift a client request over to another host.

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 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.

400 (Bad Request)

400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request message parameters, or deceptive request routing etc.

The client SHOULD NOT repeat the request without modifications.

401 (Unauthorized)

A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

The client MAY repeat the request with a suitable Authorization header field. 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.

403 (Forbidden)

A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it, i.e., the user does not have the necessary permissions for the resource. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”).

Authentication will not help, and the request SHOULD NOT be repeated. Unlike a 401 Unauthorized response, authenticating will make no difference.

404 (Not Found)

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future. Subsequent requests by the client are permissible.

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 API responds with a 405 error to indicate that the client tried to use an HTTP method that the resource does not allow. For instance, a read-only resource could support only GET and HEAD, while a controller resource might allow GET and POST, but not PUT or DELETE.

A 405 response must include the Allow header, which lists the HTTP methods that the resource supports. For example:

Allow: GET, POST

406 (Not Acceptable)

The 406 error response indicates that the API is not able to generate any of the client’s preferred media types, as indicated by the Accept request header. For example, a client request for data formatted as application/xml will receive a 406 response if the API is only willing to format data as application/json.

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.

412 (Precondition Failed)

The 412 error response indicates that the client specified one or more preconditions in its request headers, effectively telling the REST API to carry out its request only if certain conditions were met. A 412 response indicates that those conditions were not met, so instead of carrying out the request, the API sends this status code.

415 (Unsupported Media Type)

The 415 error response indicates that the API is not able to process the client’s supplied media type, as indicated by the Content-Type request header. For example, a client request including data formatted as application/xml will receive a 415 response if the API is only willing to process data formatted as application/json.

For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

500 (Internal Server Error)

500 is the generic REST API error response. Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception.

A 500 error is never the client’s fault, and therefore, it is reasonable for the client to retry the same request that triggered this response and hope to get a different response.

The API response is the generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

501 (Not Implemented)

The server either does not recognize the request method, or it cannot fulfill the request. Usually, this implies future availability (e.g., a new feature of a web-service API).

References :

https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Содержание

  • Что такое код ответа HTTP
  • Как проверить код состояния страницы
  • В браузере
  • В Яндекс.Вебмастере
  • В Google Search Console
  • 1* класс кодов (информационные сообщения)
  • 100 Continue
  • 101 Switching Protocols
  • 102 Processing
  • 103 Checkpoint
  • 105 Name Not Resolved
  • 2* класс кодов (успешно обработанные запросы)
  • 200 ОК
  • 201 Created
  • 202 Accepted
  • 203 Non‑Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi‑Status
  • 226 IM Used
  • 3* класс кодов (перенаправление на другой адрес)
  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found/Moved 
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Unused
  • 307 Temporary Redirect
  • 308 Resume Incomplete
  • 4* класс кодов (ошибки на стороне клиента)
  • 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 Request Entity Too Large
  • 414 Request‑URI Too Long
  • 415 Unsupported Media Type
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a teapot
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 425 Unordered Collection
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 434 Requested Host Unavailable
  • 444 No Response
  • 449 Retry With
  • 450 Blocked by Windows Parental Controls
  • 451 Unavailable For Legal Reasons
  • 456 Unrecoverable Error
  • 499 Client Closed Request
  • 5* класс кодов (ошибки на стороне сервера)
  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 506 Variant Also Negotiates
  • 507 Insufficient Storage
  • 508 Loop Detected
  • 509 Bandwidth Limit Exceeded
  • 510 Not Extended
  • 511 Network Authentication Required
  • Составили подробный классификатор кодов состояния HTTP. Добавляйте в закладки, чтобы был под рукой, когда понадобится.

    Что такое код ответа HTTP

    Когда посетитель переходит по ссылке на сайт или вбивает её в поисковую строку вручную, отправляется запрос на сервер. Сервер обрабатывает этот запрос и выдаёт ответ — трехзначный цифровой код HTTP от 100 до 510. По коду ответа можно понять реакцию сервера на запрос. 

    Первая цифра в ответе обозначает класс состояния, другие две — причину, по которой мог появиться такой ответ.

    Как проверить код состояния страницы

    Проверить коды ответа сервера можно вручную с помощью браузера и в панелях веб‑мастеров: Яндекс.Вебмастер и Google Search Console.

    В браузере

    Для примера возьмём Google Chrome.

    1. Откройте панель разработчика в браузере клавишей F12, комбинацией клавиш Ctrl + Shift + I или в меню браузера → «Дополнительные инструменты» → «Инструменты разработчика». Подробнее об этом рассказывали в статье «Как открыть исходный код страницы». 

    2. Переключитесь на вкладку «Сеть» в Инструментах разработчика и обновите страницу: 

    Как посмотреть код ответа сервера в инструментах разработчика в браузере

    Как посмотреть код ответа сервера в инструментах разработчика в браузере

    В Яндекс.Вебмастере

    Откройте инструмент «Проверка ответа сервера» в Вебмастере. Введите URL в специальное поле и нажмите кнопку «Проверить»:

    Как посмотреть код состояния в Вебмастере

    Как посмотреть код состояния в Вебмастере

    Как добавить сайт в Яндекс.Вебмастер и другие сервисы Яндекса

    В Google Search Console

    Чтобы посмотреть код ответа сервера в GSC, перейдите в инструмент проверки URL — он находится в самом верху панели:

    Проверка URL в инструменте GSC

    Проверка URL в инструменте GSC

    Введите ссылку на страницу, которую хотите проверить, и нажмите Enter. В результатах проверки нажмите на «Изучить просканированную страницу» в блоке «URL есть в индексе Google».

    Изучить просканированную страницу в GSC

    Изучить просканированную страницу в GSC

    А затем в открывшемся окне перейдите на вкладку «Подробнее»:

    HTTP код страницы в GSC

    HTTP код страницы в GSC

    Теперь расскажем подробнее про все классы кодов состояния HTTP.

    1* класс кодов (информационные сообщения)

    Это системный класс кодов, который только информирует о процессе передачи запроса. Такие ответы не являются ошибкой, хотя и могут отображаться в браузере как Error Code.

    100 Continue

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

    101 Switching Protocols

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

    102 Processing

    Запрос принят — он находится в обработке, и на это понадобится чуть больше времени.

    103 Checkpoint

    Контрольная точка — используется в запросах для возобновления после прерывания запросов POST или PUT.

    POST отправляет данные на сервер, PUT создает новый ресурс или заменяет существующий данными, представленными в теле запроса. 

    Разница между ними в том, что PUT работает без изменений: повторное его применение даёт такой же результат, что и в первый раз, а вот повторный вызов одного и того же метода POST часто меняет данные. 

    Пример — оформленный несколько раз интернет‑заказ. Такое часто происходит как раз по причине неоднократного использования запроса PUT.

    105 Name Not Resolved

    Не удается преобразовать DNS‑адрес сервера — это  означает ошибку в службе DNS. Эта служба преобразует IP‑адреса в знакомые нам доменные имена.

    2* класс кодов (успешно обработанные запросы)

    Эти коды информируют об успешности принятия и обработки запроса. Также сервер может передать заголовки или тело сообщений. 

    200 ОК

    Все хорошо — HTTP‑запрос успешно обработан (не ошибка).

    201 Created

    Создано — транзакция успешна, сформирован новый ресурс или документ.

    202 Accepted

    Принято — запрос принят, но ещё не обработан.

    203 Non‑Authoritative Information

    Информация не авторитетна — запрос успешно обработан, но передаваемая информация была взята не из первичного источника (данные могут быть устаревшими).

    204 No Content

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

    205 Reset Content

    Сбросить содержимое. Запрос успешно обработан — но нужно сбросить введенные данные. Страницу можно не обновлять.

    206 Partial Content

    Частичное содержимое. Сервер успешно обработал часть GET‑запроса, а другую часть вернул.

    GET — метод для чтения данных с сайта. Он говорит серверу, что клиент хочет прочитать какой‑то документ. 

    Представим интернет‑магазин и страницы каталога. Фильтры, которые выбирает пользователь, передаются благодаря методу GET. GET‑запрос работает с  получением данных, а POST‑запрос нужен для отправки данных.

    При работе с подобными ответами следует уделить внимание кэшированию.

    207 Multi‑Status

    Успешно выполнено несколько операций — сервер передал результаты выполнения нескольких независимых операций. Они появятся в виде XML‑документа с объектом multistatus. 

    226 IM Used

    Успешно обработан IM‑заголовок (специальный заголовок, который отправляется клиентом и используется для передачи состояния HTTP).

    3* класс кодов (перенаправление на другой адрес)

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

    300 Multiple Choices

    Множественный выбор — сервер выдает список нескольких возможных вариантов перенаправления (максимум — 5). Можно выбрать один из них.

    301 Moved Permanently

    Окончательно перемещено — страница перемещена на другой URL, который указан в поле Location.

    302 Found/Moved 

    Временно перемещено — страница временно перенесена на другой URL,  который указан в поле Location.

    303 See Other

    Ищите другую страницу — страница не найдена по данному URL, поэтому смотрите страницу по другому URL, используя метод GET.

    304 Not Modified

    Модификаций не было — с момента последнего визита клиента изменений не было.

    305 Use Proxy

    Используйте прокси — запрос к нужному ресурсу можно сделать только через прокси‑сервер, URL которого указан в поле Location заголовка.

    306 Unused

    Зарезервировано. Код в настоящий момент не используется.

    307 Temporary Redirect

    Временное перенаправление — запрашиваемый ресурс временно доступен по другому URL.

    Этот код имеет ту же семантику, что код ответа 302 Found, за исключением того, что агент пользователя не должен изменять используемый метод HTTP: если в первом запросе использовался POST, то во втором запросе также должен использоваться POST.

    308 Resume Incomplete

    Перемещено полностью (навсегда) — запрашиваемая страница была перенесена на новый URL, указанный в поле Location заголовка. Метод запроса (GET/POST) менять не разрешается.

    4* класс кодов (ошибки на стороне клиента)

    Эти коды указывают на ошибки со стороны клиентов. 

    Скриншот страницы с ошибкой 404 с сайта modcloth.com

    Скриншот страницы с ошибкой 404 с сайта modcloth.com

    400 Bad Request

    Неверный запрос — запрос клиента не может быть обработан, так как есть синтаксическая ошибка (возможно, опечатка).

    401 Unauthorized

    Не пройдена авторизация — запрос ещё в обработке, но доступа нет, так как пользователь не авторизован.

    Для доступа к запрашиваемому ресурсу клиент должен представиться, послав запрос, включив при этом в заголовок сообщения поле Authorization.

    402 Payment Required

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

    403 Forbidden

    Запрещено — запрос принят, но не будет обработан, так как у клиента недостаточно прав. Может возникнуть, когда пользователь хочет открыть системные файлы (robots, htaccess) или не прошёл авторизацию.

    404 Not Found

    Не найдено — запрашиваемая страница не обнаружена. Сервер принял запрос, но не нашёл ресурса по указанному URL (возможно, была ошибка в URL или страница была перемещена).

    405 Method Not Allowed

    Метод не разрешён — запрос был сделан методом, который не поддерживается данным ресурсом. Сервер должен предложить доступные методы решения в заголовке Allow.

    406 Not Acceptable

    Некорректный запрос — неподдерживаемый поисковиком формат запроса (поисковый робот не поддерживает кодировку или язык).

    407 Proxy Authentication Required

    Нужно пройти аутентификацию прокси — ответ аналогичен коду 401, только нужно аутентифицировать прокси‑сервер.

    408 Request Timeout

    Тайм‑аут запроса — запрос клиента занял слишком много времени. На каждом сайте существует свое время тайм‑аута — проверьте интернет‑соединение  и просто обновите страницу.

    409 Conflict

    Конфликт (что‑то пошло не так) — запрос не может быть выполнен из‑за конфликтного обращения к ресурсу (несовместимость двух запросов).

    410 Gone

    Недоступно — ресурс раньше был размещён по указанному URL, но сейчас удалён и  недоступен (серверу неизвестно месторасположение).

    411 Length Required

    Добавьте длины — сервер отклоняет отправляемый запрос, так как длина заголовка не определена, и он не находит значение Content‑Length. 

    Нужно исправить заголовки на сервере, и в следующий раз робот сможет проиндексировать страницу.

    412 Precondition Failed

    Предварительное условие не выполнено — стоит проверить правильность HTTP‑заголовков данного запроса.

    413 Request Entity Too Large

    Превышен размер запроса — перелимит максимального размера запроса, принимаемого сервером. Браузеры поддерживают запросы от 2 до 8 килобайт.

    414 Request‑URI Too Long

    Превышена длина запроса — сервер не может обработать запрос из‑за длинного URL. Такая ошибка может возникнуть, например, когда клиент пытается передать чересчур длинные параметры через метод GET, а не POST.

    415 Unsupported Media Type

    Формат не поддерживается —  сервер не может принять запрос, так как  данные подгружаются в некорректном формате, и сервер разрывает соединение.

    416 Requested Range Not Satisfiable

    Диапазон не поддерживается — ошибка возникает в случаях, когда в самом HTTP‑заголовке прописывается некорректный байтовый диапазон.

    Корректного диапазона в необходимом документе может просто не быть, или есть опечатка в синтаксисе.

    417 Expectation Failed

    Ожидания не оправдались — прокси некорректно идентифицировал содержимое поля «Expect: 100‑Continue».

    418 I’m a teapot

    Первоапрельская шутка разработчиков в 1998 году. В расшифровке звучит как «я не приготовлю вам кофе, потому что я чайник». Не используется в работе.

    422 Unprocessable Entity

    Объект не обработан — сервер принял запрос, но в нём  есть логическая ошибка. Стоит посмотреть в сторону семантики сайта.

    423 Locked

    Закрыто — ресурс заблокирован для выбранного HTTP‑метода. Можно перезагрузить роутер и компьютер. А также использовать только статистический IP.

    424 Failed Dependency

    Неуспешная зависимость — сервер не может обработать запрос, так как  один из зависимых ресурсов заблокирован.

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

    425 Unordered Collection

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

    426 Upgrade Required

    Нужно обновление — в заголовке ответа нужно корректно сформировать поля Upgrade и Connection. 

    Этот ответ возникает, когда серверу требуется обновление до SSL‑протокола, но клиент не имеет его поддержки.

    428 Precondition Required

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

    429 Too Many Requests

    Слишком много запросов — отправлено слишком много запросов за короткое время. Это может указывать, например, на попытку DDoS‑атаки, для защиты от которой запросы блокируются.

    431 Request Header Fields Too Large

    Превышена длина заголовков — сервер может и не отвечать этим кодом, вместо этого он может просто сбросить соединение.

    Исправляется это с помощью сокращения заголовков и повторной отправки запроса.

    434 Requested Host Unavailable

    Адрес запрашиваемой страницы недоступен.

    444 No Response

    Нет ответа — код отображается в лог‑файлах, чтобы подтвердить, что сервер никак не отреагировал на запрос пользователя и прервал соединение. Возвращается только сервером nginx.

    Nginx — программное обеспечение с открытым исходным кодом. Его используют для создания веб‑серверов, а также  в качестве почтового или обратного прокси‑сервера. Nginx решает проблему падения производительности из‑за роста трафика. 

    449 Retry With

    Повторите попытку — ошибка говорит о необходимости скорректировать запрос и повторить его снова. Причиной становятся неверно указанные параметры (возможно, недостаточно данных).

    450 Blocked by Windows Parental Controls

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

    451 Unavailable For Legal Reasons

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

    456 Unrecoverable Error

    Неустранимая ошибка — при обработке запроса возникла ошибка, которая вызывает некорректируемые сбои в таблицах баз данных.

    499 Client Closed Request

    Запрос закрыт клиентом — нестандартный код, используемый nginx в ситуациях, когда клиент закрыл соединение, пока nginx обрабатывал запрос.

    5* класс кодов (ошибки на стороне сервера)

    Эти коды указывают на ошибки со стороны серверов. 

    При использовании всех методов, кроме HEAD, сервер должен вернуть в теле сообщения гипертекстовое пояснение для пользователя. И его можно использовать в работе.

    Изображение страницы с ошибкой сайта REG.RU

    Изображение страницы с ошибкой сайта REG.RU

    500 Internal Server Error

    Внутренняя ошибка сервера — сервер столкнулся с неким условием, из‑за которого не может выполнить запрос. 

    Проверяйте, корректно ли указаны директивы в системных файлах (особенно htaccess) и нет ли ошибки прав доступа к файлам. Обратите внимание на ошибки внутри скриптов и их медленную работу.

    501 Not Implemented

    Не выполнено —  код отдается, когда сам сервер не может идентифицировать метод запроса. 

    Сами вы эту ошибку не исправите. Устранить её может только сервер.

    502 Bad Gateway

    Ошибка шлюза — появляется, когда сервер, выступая в роли шлюза или прокси‑сервера, получил ответное сообщение от вышестоящего сервера о несоответствии протоколов.

    Актуально исключительно для прокси и шлюзовых конфигураций.

    503 Service Unavailable

    Временно не доступен — сервер временно не имеет возможности обрабатывать запросы по техническим причинам (обслуживание, перегрузка и прочее). 

    В поле Retry‑After заголовка сервер укажет время, через которое  можно повторить запрос.

    504 Gateway Timeout

    Тайм‑аут шлюза —  сервер, выступая в роли шлюза или прокси‑сервера, не получил ответа от вышестоящего сервера в нужное время.

    Исправить эту ошибку самостоятельно не получится. Здесь дело в прокси, часто — в веб‑сервере. 

    Первым делом просто обновите веб‑страницу. Если это не помогло, нужно почистить DNS‑кэш. Для этого  нажмите горячие клавиши Windows+R и введите команду cmd (Control+пробел). В открывшемся окне укажите команду ipconfig / flushdns и подтвердите её нажатием Enter.

    505 HTTP Version Not Supported

    Сервер не поддерживает версию протокола — отсутствует поддержка текущей версии HTTP‑протокола. Нужно обеспечить клиента и сервер одинаковой версией.

    506 Variant Also Negotiates

    Неуспешные переговоры — с такой ошибкой сталкиваются, если сервер изначально настроен неправильно. По причине ошибочной конфигурации выбранный вариант указывает сам на себя, из‑за чего процесс и прерывается.

    507 Insufficient Storage

    Не хватает места для хранения — серверу недостаточно места в хранилище. Нужно либо расчистить место, либо увеличить доступное пространство.

    508 Loop Detected

    Обнаружен цикл — ошибка означает провал запроса и выполняемой операции в целом.

    509 Bandwidth Limit Exceeded

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

    510 Not Extended

    Не продлён — ошибка говорит, что на сервере отсутствует нужное для клиента расширение. Чтобы исправить проблему, надо убрать часть неподдерживаемого расширения из запроса или добавить поддержку на сервер.

    511 Network Authentication Required

    Требуется аутентификация — ошибка генерируется сервером‑посредником, к примеру, сервером интернет‑провайдера, если нужно ввести пароль для получения доступа к сети через платную точку доступа.

    Понравилась статья? Поделить с друзьями:
  • Http error 204
  • Http error 12157
  • Http error 12002
  • Http error 111
  • Http error 1020