Skip to content
4124xx · Client errorThe client seems to have erred. RFC 9110 §15.5

HTTP 412 Precondition Failed: meaning and how to fix it

Meaning

HTTP 412 Precondition Failed means an If-Match, If-None-Match or If-Unmodified-Since check came out false. Causes, a local repro and fixes.

HTTP 412 means your request carried a condition, the server tested it against the current state of the resource, and the test came out false, so the server refused to run the method. The reason phrase is “Precondition Failed”, defined in RFC 9110, section 15.5.13. The conditions are request headers from section 13 of the same RFC, and only three of them can produce a 412:

  • If-Match, when none of the listed entity tags matches the current one;
  • If-Unmodified-Since, when the resource changed after the given date;
  • If-None-Match on a method other than GET or HEAD, when the tag does match. On GET and HEAD the same failure gives 304 Not Modified instead.

If-Modified-Since never causes a 412. Its failure is always a 304.

The point of all this is to stop lost updates. Two clients read a document, both edit it, and the second write would silently overwrite the first. With If-Match carrying the tag it read, the second client gets a 412 instead.

Reproduce it locally

A small Python server keeps one document with an ETag and enforces If-Match and If-None-Match on PUT:

# etag_server.py: one document, guarded by If-Match and If-None-Match
from http.server import BaseHTTPRequestHandler, HTTPServer

doc = {"version": 2, "body": b"price=19\n"}

def etag():
    return f'"v{doc["version"]}"'

class Handler(BaseHTTPRequestHandler):
    def reply(self, code, body=b""):
        self.send_response(code)
        self.send_header("ETag", etag())
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        self.reply(200, doc["body"])

    def do_PUT(self):
        data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if_match = self.headers.get("If-Match")
        if if_match is not None and if_match != "*":
            # strong comparison: a W/ tag never matches
            tags = [t.strip() for t in if_match.split(",")]
            if etag() not in tags:
                return self.reply(412)
        if self.headers.get("If-None-Match") == "*":
            return self.reply(412)  # the document already exists
        doc["version"] += 1
        doc["body"] = data
        self.reply(204)

HTTPServer(("127.0.0.1", 8412), Handler).serve_forever()

Start it with python3 etag_server.py. Real output from Python 3.15.0 and curl 8.7.1, Date header removed:

$ curl -si http://127.0.0.1:8412/doc | grep -v '^Date:'
HTTP/1.0 200 OK
Server: BaseHTTP Python/3.15.0
ETag: "v2"
Content-Length: 9

price=19
$ curl -si -X PUT -H 'If-Match: "v1"' --data 'price=21' http://127.0.0.1:8412/doc | grep -v '^Date:'
HTTP/1.0 412 Precondition Failed
Server: BaseHTTP Python/3.15.0
ETag: "v2"
Content-Length: 0

$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H 'If-Match: W/"v2"' --data 'price=21' http://127.0.0.1:8412/doc
412
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H 'If-None-Match: *' --data 'price=21' http://127.0.0.1:8412/doc
412
$ curl -s -o /dev/null -w '%{http_code} %header{etag}\n' -X PUT -H 'If-Match: "v2"' --data 'price=21' http://127.0.0.1:8412/doc
204 "v3"

Four writes, three refusals. "v1" is stale. W/"v2" names the right version but is weak, and section 13.1.1 requires the strong comparison for If-Match, under which a weak tag never matches anything. If-None-Match: * means “only if nothing exists here yet”, which is false. The last request names the current strong tag, so the write goes through and the tag moves on to "v3".

The weak ETag trap, on a real nginx

The weak-tag case is not hypothetical. We sent the same requests to the nginx origin that serves this site’s robots.txt. Fetched plainly, the file carries ETag: "6a9336b4-4b1". Fetched with Accept-Encoding: gzip, nginx compresses it and hands out W/"6a9336b4-4b1" instead. Sent back in If-Match, the strong form returned 200, while the weak form and a made-up tag both returned 412. A client that saves the tag from a compressed response and echoes it in If-Match will be refused every time.

Through the CDN in front of the origin, the same made-up tag passes:

$ curl -s -o /dev/null -w '%{http_code} %header{cf-cache-status} %header{etag}\n' -H 'If-Match: "nope"' https://proxy.wiki/robots.txt
200 HIT W/"6a9336b4-4b1"

That is consistent with the RFC. Its evaluation order in section 13.2.2 applies If-Match and If-Unmodified-Since only when the recipient is the origin server, and this answer came from the edge cache. The practical result is that one request can succeed on a cache hit and fail with 412 on a miss.

A reverse proxy or CDN can also send 412 for its own reasons. Amazon CloudFront’s documentation lists conditional requests on methods other than GET and HEAD, and a false condition on its UpdateDistribution API call, among its causes.

When a scraper or proxy hits it

Scrapers rarely set these headers on purpose. They arrive by copying. A request exported from browser devtools or replayed from a HAR file brings along the browser’s If-None-Match and If-Modified-Since validators. On a GET those only cost you a 304 with an empty body. On a replayed POST or PUT that carries If-Match or If-None-Match, a stale tag is a 412. What a clean client sends without any of this is measured in what HTTP clients send by default.

A forward proxy passes conditional headers through unchanged, so it is rarely the cause. When a 412 comes and goes between exits or retries, suspect the path instead: two origin servers behind a load balancer that compute different tags for the same file, or a cache that answered one request while the origin answered the next. Keeping the same exit for a read-modify-write sequence, as described in rotating vs sticky sessions, removes one variable.

Never retry a 412 unchanged. The condition is false and stays false until you re-read the resource.

Header in your request Why it failed What to change
If-Match: "old-tag" The resource changed after you read it GET it again, apply your change to the fresh copy, resend with the new tag
If-Match: W/"tag" A weak tag under strong comparison, often saved from a gzipped response Read the tag from an uncompressed response, or use If-Unmodified-Since where the API accepts it
If-None-Match: * on PUT or POST The resource already exists Update with If-Match instead, or write to a new URL
If-Unmodified-Since The resource was modified after that date Re-read Last-Modified and decide whether your change still applies
Validators copied from a browser or HAR Replayed tags and dates no longer describe the current resource Strip If-* headers from replayed requests unless your code manages them
Any, but only on some exits or retries Different backends or a cache answering some requests Use one sticky session for the sequence and compare Server and Age headers

To send these headers through a proxy from the command line, see how to use a proxy with curl.

Frequently asked questions

What is the difference between 412 and 304?
Both come from a false condition. On GET and HEAD, a failed If-None-Match or If-Modified-Since gives 304 Not Modified, which means your cached copy is still good. A failed If-Match or If-Unmodified-Since, or a failed If-None-Match on a write, gives 412 and the method is not run.
Why does If-Match fail when I send the ETag the server gave me?
Usually because the tag is weak, written W/"...". If-Match uses strong comparison, under which a weak tag never matches. The nginx we tested hands out a weak tag when it compresses a response, so read the tag from an uncompressed response.
Is a 412 a sign that a site is blocking my scraper?
In its standard meaning, no. It says a condition you sent was false. Check your request for If-* headers first, especially ones copied from a browser or a HAR file.
Should I retry a 412?
Not unchanged, because the condition stays false. Fetch the resource again, take the current ETag or Last-Modified value, reapply your change and send it with the new value.

Sources

  1. RFC 9110: HTTP Semantics, section 15.5.13, 412 Precondition Failed
  2. RFC 9110, section 13.1.1: If-Match
  3. RFC 9110, section 13.2.2: Precedence of Preconditions
  4. RFC 9110, section 8.8.3.2: entity tag comparison
  5. Amazon CloudFront Developer Guide: HTTP 412 status code (Precondition Failed)
  6. IANA: HTTP Status Code Registry

All terms, A to Z