412 Предупреждение Ошибка
Протокол передачи гипертекста (HTTP) 412 Precondition Failed
client error response code указывает, что доступ к целевому ресурсу был запрещен. Это происходит с условными запросами к методам, отличным от GET
или HEAD
, когда условие, определенное заголовками If-Unmodified-Since
или If-None-Match
, не выполняется. В этом случае запрос, обычно загрузка или изменение ресурса, не может быть выполнен, и этот ответ об ошибке отправляется обратно.
Status
Examples
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ETag: W/"0815"
Предотвращение столкновений в воздухе
С помощью ETag
и If-Match
вы можете обнаруживать конфликты редактирования в воздухе.
Например, при редактировании MDN текущий контент вики хешируется и помещается в Etag
в ответе:
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
При сохранении изменений на вики-странице (данные публикации) запрос POST
будет содержать заголовок If-Match
, содержащий значения ETag
, по которым выполняется проверка актуальности .
If-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Если хэши не совпадают, это означает, что документ был отредактирован между ними, и Precondition Failed
ошибка 412
Precondition Failed .
Specifications
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox для Android | Opera Android | Safari на IOS | Samsung Internet | |
412 |
Yes |
12 |
Yes |
Yes |
Yes |
Yes |
Yes |
Yes |
Yes |
Yes |
Yes |
Yes |
See also
304
If-Unmodified-Since
If-None-Match
428
HTTP
-
410 Gone
Код ответа ошибки клиента HyperText Transfer Protocol (HTTP)410 Gone указывает,что доступ к целевому ресурсу больше не доступен серверу происхождения и
-
411 Требуемая длина
Код ошибки ответа клиента HyperText Transfer Protocol (HTTP)411 Length Required указывает,что сервер отказывается принимать запрос без определенной Content-Length.
-
413 Слишком большая грузоподъемность
Код состояния ответа HTTP 413 Payload Too Large указывает на то,что объект запроса превышает пределы,определенные сервером;возможно закрытие соединения или возврат Retry-After
-
414 УРТ слишком длинный
Код состояния ответа HTTP 414 URI Too Long указывает на то,что запрос клиента длиннее,чем сервер готов интерпретировать.
HTTP response status code 412 Precondition Failed is a client error that is returned by the server to indicate that one or more of the client-specified conditions in the request has failed. Due to this failure, the request was not completed.
Usage
When the 412 Precondition Failed error message is received, the client will know that one or more of the conditions that are specified in the request has failed, and as such, the resource was not in the expected state. This happens for HTTP requests that are not of type HTTP method HEAD or HTTP method GET.
This is similar to response 304 Not Modified, although in that case, a resource was not sent to the client in response to an HTTP method HEAD or GET request because the client already had the most recent version available, and a subsequent transmission will be a waste of bandwidth.
Note
Search engines like Google will not index a URL with 412 Precondition Failed response status, and consequently, URLs that have been indexed in the past but are now returning this HTTP status code will be removed from the search results.
Example
In the example, the client wants to reply to a blog post, but only under the condition that the post has not been changed since the client last viewed it. The condition is contained as part of the If-Unmodified-Since header. When it fails, it is because the resource has indeed been modified, and the server responds with 412 Precondition Failed to indicate that the request was not completed.
By following this protocol, the problem of having a ‘lost update’ is avoided. Lost updates occur when multiple people are writing to the same resource, and one or more is working with an outdated version. By ensuring that the resource has not been modified, they are guaranteed not to overwrite or modify data that has been modified in the interim.
It is easy to imagine that without this in place, notes in a live document can be overwritten because a subsequent update had been initiated before the start and finish of a shorter one. The shorter one will be overwritten because the subsequent post has cached an older version and with its updates applied, rewrite the entire file.
Request
POST /blog/update?postid=111&task=reply HTTP/1.1
Host: www.example.re
If-Unmodified-Since: Fri, 1 Jan 2021 00:00:00 GMT
Content-Type: text/plain
Content-Length: 45
<Message body contains reply-text from the client>
Response
HTTP/1.1 412 Precondition Failed
Content-Type: text/html
Content-Length: 182
<html>
<head>
<title>Blog Update Error</title>
</head>
<body>
<p>The post has changed since you last viewed it, so your reply will not be recorded.</p>
</body>
</html>
Code references
.NET
HttpStatusCode.PreconditionFailed
Rust
http::StatusCode::PRECONDITION_FAILED
Rails
:precondition_failed
Go
http.StatusPreconditionFailed
Symfony
Response::HTTP_PRECONDITION_FAILED
Python3.5+
http.HTTPStatus.PRECONDITION_FAILED
Java
java.net.HttpURLConnection.HTTP_PRECON_FAILED
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_PRECONDITION_FAILED
Angular
@angular/common/http/HttpStatusCode.PreconditionFailed
Takeaway
The 412 Precondition Failed status code is a client error sent in response to an HTTP request that is not of type HTTP method HEAD or HTTP method GET, indicating that one of the specified conditions has failed and that the request will not be completed.
See also
- RFC 7232 HTTP response status code 412 Precondition Failed is a client error that is returned by the server to indicate that one or more of the client-specified conditions in the request has failed. Due to this failure, the request was not completed.
Last updated: August 2, 2023
One or more conditions given in the request header fields evaluated to false when tested on the server.
This response code allows the client to place preconditions on the current resource state (its current representations and metadata) and, thus, prevent the request method from being applied if the target resource is in an unexpected state.
- Source: RFC7232 Section 4.2
412 CODE REFERENCES
Rails HTTP Status Symbol :precondition_failed
Go HTTP Status Constant http.StatusPreconditionFailed
Symfony HTTP Status Constant Response::HTTP_PRECONDITION_FAILED
Python2 HTTP Status Constant httplib.PRECONDITION_FAILED
Python3+ HTTP Status Constant http.client.PRECONDITION_FAILED
Python3.5+ HTTP Status Constant http.HTTPStatus.PRECONDITION_FAILED
When is a 412 status code used?
An HTTP 412 status code is used for HTTP requests are not HTTP method HEAD or HTTP method GET.
When the 412 precondition failed error message is received, the client will know that one or more of the conditions in the request has failed and the resource will not be retrieved in the expected format or state.
Will search engines index a URL with a 412 status code?
No. Search engines like Google will not index a URL with the HTTP 412 precondition failed status code. That means that URLs that have been previously indexed but are now returning a 412 response status will likely suffer a loss in their search result rankings.
412 status code example
Want to see a 412 response code in action? Check out the 412 example below. In this example, the client is requesting to leave a comment on an article but only wants their response to be recorded if the article hasn’t been updated since they last viewed it.
If this article has been modified, the server will respond with a 412 precondition failed status error to demonstrate that the client’s request hasn’t been fulfilled.
Request
POST /examplearticle/update?postid=123&task=reply HTTP/1:1
Host: www.example.com
If-unmodified-since: 13 March 2023 0:00:00 GMT
Content-type: text/plain
Content length: 30
<message body from client>
Response
HTTP/1:1 412 Precondition Failed
Content type: text/plain
Content length: 60
<html>
<head>
<title> Article Update Error <title>
<head>
<body>
<p> This article has been updated since you recorded your comment, so your response will not be posted.<>;p>
<body>
</html>
Which browsers are compatible with a 412 response code?
The following browsers will issue an HTTP 412 response code:
- Google Chrome
- Microsoft Edge
- Firefox
- Opera
- Safari
- Chrome Android
- Safari on iOS
- Samsung Internet
WebView Android
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
The 412 HTTP Status Code means that the request is preconditioned failed. When one or more of the conditions specified in the request header fields were tested on the server, the precondition failed. The 412 HTTP Status Code enables the client to impose preconditions on the current resource state, representations, and metadata, preventing the request method from being applied if the target resource is in an unexpected state. The difference between the 412 HTTP Status Code and the 400 HTTP Status Code is that the 400 HTTP Status Codes could not understand the request due to invalid syntax, whereas the 412 HTTP Status Code indicates that access to the target resource has been denied.
What does 412 HTTP Status Code Mean?
The 412 HTTP Status Code Precondition Failed access to the target resource has been denied due to a failed client error response code. When the condition defined by the If-Unmodified-Since or If-None-Match headers is not met, this occurs with conditional requests on methods other than GET or HEAD. In that case, the request, which is usually an upload or a resource modification, cannot be completed, and this error response is returned.
How to Use 412 HTTP Status Code for a Website?
To use the 412 HTTP status code in a website, the web developer should be aware of Precondition Failed, which means that a specific configuration is required for this file to be delivered, but the browser client has not set this up. When tested on the server, one or more of the conditions specified in the request header fields were found to be false. This response code enables the client to impose preconditions on the current resource state (its current representations and metadata), preventing the request method from being applied if the target resource is in an unexpected state.
How to Check 412 HTTP Status Code?
To check the 412 HTTP Status Code use the web browser network tab and developer tools for every resource that the client uses.
Which HTTP Method is used with 412 HTTP Status Code?
There are multiple HTTP Methods that are used with 412 HTTP Status Code. The following HTTP Method is listed below.
- GET HTTP Method: The GET method asks for a representation of the given resource. Requests using GET should only retrieve data. As a standard request HTTP method, the GET HTTP method is used with the 412 HTTP Status Code.
- HEAD HTTP Method: As a standard HTTP request method, the GET HTTP method is used with the 412 HTTP Status Code. As a standard request HTTP method, the HEAD HTTP Method is used in conjunction with the 412 HTTP Status Code.
There are multiple related HTTP Response Headers with the 412 HTTP Status Code. The following related HTTP Response Headers are listed below.
- If-Unmodified-Since HTTP Header: The If-Unmodified-Since HTTP Header request header conditions the resource request: the server will send the requested resource or accept it in the case of a POST or another non-safe method only if the resource has not been modified since the date specified by this HTTP header. If the resource has been modified after the specified date, a 412 Precondition Failed error will be returned.
- If-Non-Match HTTP Header: The HTTP request header If-None-Match makes the request conditional. The server will return the requested resource with a 200 status for GET and HEAD methods only if it does not have an ETag that matches the given ones. In the case of other methods, the request will be processed only if the ETag of the eventually existing resource does not match any of the values listed.
What are the Browsers Compatibility of 412 HTTP Status Code?
You can see the table that shows the browser’s compatibility with the 412 HTTP Status Code below.
Browser Name | Browser Compatibility of 412 HTTP Status Code |
Chrome | YES |
Edge | YES |
Firefox | YES |
Internet Explorer | YES |
Opera | YES |
Safari | YES |
WebView Android | YES |
What are the other Similar Status Codes to 412 HTTP Status Code?
There are other similar HTTP Status Codes to 412 HTTP Status Code. The following HTTP Status Codes are listed below.
- 411 Length Required HTTP Status Code: The request was rejected by the server because the Content-Length header field was not defined, despite the fact that the server requires it. The 411 HTTP Status Code is similar to the 412 HTTP Status Code which is also a client error response.
- 413 Payload Too Large HTTP Status Code: Request entity is larger than limits defined by the server. The server might close the connection or return a Retry-After header field. The 413 HTTP Status Code is similar to the 412 HTTP Status Code which is also a client error response.
- 414 URI Too Long HTTP Status Code: The client’s URI is longer than the server is willing to interpret. The 414 HTTP Status Code is similar to the 412 HTTP Status Code which is also a client error response.
- 415 Unsupported Media Type HTTP Status Code: The server does not support the requested data’s media format, so the request is rejected. The 415 HTTP Status Code is similar to the 412 HTTP Status Code which is also a client error response.
- Author
- Recent Posts
Holistic SEO & Digital has been built by Koray Tuğberk GÜBÜR. Holistic SEO is the process of developing integrated digital marketing projects with every aspect including Coding, Natural Language Processing, Data Science, Page Speed, Digital Analytics, Content Marketing, Technical SEO, and Branding. Structured, Semantic Search Engine improves its ability to detect the real-world entities, today. Having a simple website is not enough anymore. To show that your brand is authoritative, trustworthy, and expert on its own niche, you need entity-based Search Engine Optimization Projects. Holistic SEO & Digital’s main focus is on improving the brand’s organic visibility and growth potential.
When you’re troubleshooting an issue related to web development, it can be frustrating not knowing what’s causing the problem. A common one that many developers run into is known as HTTP 412 precondition failed. This error involves a server refusing access when certain requirements or preconditions are not met by the client. In this blog post, we’ll discuss what exactly HTTP 412 precondition failed is and how you can fix it.
What are the http status codes?
HTTP status codes are three-digit numbers that are returned by a web server in response to a client’s request using the HTTP (hypertext transfer protocol). These codes indicate the status of the request and whether it was successful or not. Some common status codes include 200 OK, 404 Not Found, and 500 Internal Server Error.
These codes can be separated into five classes, with the initial digit in each http status code showing which class it falls into. Here is an overview of these categories:
- 1xx: Informational – These codes verify that your request has been acknowledged and is currently being processed.
- 2xx: Successful – An indication of success, these codes signify that the requested resource is being sent back to you. You can rest assured knowing that your request has been fulfilled!
- 3xx: Redirection – To complete the request, clients must adhere to these codes that signify further steps of action.
- 4xx: Client Error – These codes demonstrate that the client’s inquiry contained a mistake, such as an excluded or incorrect parameter.
- 5xx: Server Error – These codes signalize that the server encountered an issue and couldn’t process the initial request.
What is 412 http status code?
The 412 Precondition Failed client error response code is one of the HTTP status codes that indicate that a request failed due to non-proper structured data and precondition that was not met. This error code is used when a client sends conditional requests, such as an “If-Match” or “If-Unmodified-Since” header, and the server determines that the precondition has not been met.
Causes of 412 Precondition Failed error code
Causes of 412 Precondition Failed error code:
- If a client submits an “If-Match” or “If-Unmodified-Since” request, but the server finds that their precondition has not been fulfilled, they will receive a 412 Precondition Failed error. As an example, if the customer is posting data in a POST request method with an ETag that is different than what is currently saved on the resource for whatever reason; then this response code will be received.
- If a client sends an “If-None-Match” or “If-Modified-Since” request (usually an upload) with the same ETag as the current version of their resource, then they will receive a 412 Precondition Failed error from the server. For example – if your client has requested an update and sent you an up-to-date ETag, then receiving this response would indicate that your preconditions have been met.
- When a client sends out an inquiry with the “Range” header but unfortunately meets preconditions that are not fulfilled, it results in returning 412 Precondition Failed error. For instance, if the customer’s Range request consists of unavailable information from the server – then this is what happens.
- If a client sends request header fields such as an “Expect” header with their request, but the server finds that its precondition has not been met, it will respond by sending back a 412 Precondition Failed error. As an example of this being applied in practice, if the customer includes an “Expect: 100-continue” header and the server sees that it cannot handle such a request, then perceives this as one for which prerequisites have not been fulfilled.
- The client sends a request using the http method and having their “Content-Length” header, however, if the server finds that the precondition has not been satisfied they will respond with a 412 Precondition Failed error. As an example, when the “Content-Length” sent by the client does not correspond to that of its body’s actual length then this response is triggered.
Server-side or client-side error
When the server fails to meet a condition set forth in an “If-Match” or “If-Unmodified-Since” header sent by the client, it will respond with a 412 Precondition Failed error. This is an issue that arises on the server’s side–though it may very well be due to incorrect information provided by the client initially–and indicates that the processing of this specific request has been denied.
How to fix the 412 error code
Fixes of 412 Precondition Failed error code:
- Guarantee that the indicated conditions in the request headers are fulfilled for optimal performance.
- To ensure a successful transaction, confirm that the ETag or last-modified date specified in an “If-Match” or “If-Unmodified-Since” header corresponds to the value of the target resource.
- Confirm that the ETag or last-modified date of your resource does not coincide with the value in either an “If-None-Match” or “If-Modified-Since” header if you utilize such a header.
- Before utilizing a “Range” header, make sure the range specified is accessible.
- Ensure that the server is capable of handling the request if you are using an “Expect” header.
- To ensure the accuracy of your “Content-Length” header, always confirm that its value corresponds to the length of the request body.
- Guarantee that the server is optimally set up to meet the request, and ensure there are no glitches in either the server or network which could hinder the process.
How to prevent 412 Precondition Failed error
How to prevent 412 Precondition Failed error:
- Make sure that the client is sending requests with the correct preconditions.
- To guarantee the server is appropriately set up to process the requirements stated in the request headers, make sure all necessary adjustments are done.
- To guarantee that both the client and server are responding to requests as well as preconditions accurately, verifying them is essential.
- To ensure optimal performance, be sure to regularly monitor the server logs for any potential issues that could lead to a 412 Precondition Failed error. Quickly addressing any problems will help you prevent future errors and keep your system running smoothly.
- Track the performance of both the server and network to make sure they are not the source of any issues.
- To provide users with the right information and direction, it is essential to incorporate accurate error handling in both the client and server so that 412 Precondition Failed errors are handled properly.
Similar http status codes
The HTTP Status Code 411 Length Required indicates that the server has refused to process your request as there was no Content-Length header field included. This error is similar to another client error response, 412 HTTP Status Code. It’s essential that all requests include this particular field for proper execution on the server side.
413 Payload Too Large HTTP Status Code: When the request from a client exceeds the server’s limits, its connection will be closed or a Retry-After header field returned. This is essentially equivalent to HTTP Status Code 412, which also signals a client error response.
414 URI Too Long HTTP Status Code: When a client sends too long of a URI to the server, their request is rejected. This situation resembles the 412 HTTP Status Code (a type of client error response).
415 Unsupported Media Type HTTP Status Code: If the media format of the information desired is not accepted by the server, a request for that data will be declined. This error resembles HTTP Status Code 412, which also signals an issue with client submission.