Understanding HTTP 406 Not Acceptable: Accept Headers, Default Representations, and the WAF Red Herring
406 Not Acceptable is the server saying "I have this resource, just not in any form you said you'd take." It's about the response format, which makes it the mirror image of 415, the code for an unsupported request format. It's also an error the spec lets you skip: a server may ignore the client's preferences and send its usual format instead. This post covers how content negotiation works, when a default beats a 406, why a 406 in the wild is often a firewall block in disguise, and how to return one in Express and Next.js with Vary: Accept.
What Is a 406?
A 406 means the server looked at the client's negotiation headers (Accept, Accept-Language, Accept-Encoding, Accept-Charset), found no representation that satisfies them, and chose to say so rather than send something else.
The 406 (Not Acceptable) status code indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request (Section 12.1), and the server is unwilling to supply a default representation. — RFC 9110, Section 15.5.7
In plain English: "You asked for XML. I only have JSON, and rather than send it anyway, I'm telling you." Note the last clause: the server is unwilling to supply a default representation. A 406 is a choice, not something the server is forced into.
The RFC also says what a 406 should contain:
The server SHOULD generate content containing a list of available representation characteristics and corresponding resource identifiers from which the user or user agent can choose the one most appropriate. — RFC 9110, Section 15.5.7
A good 406 isn't a dead end. It's a menu.
How Content Negotiation Works
HTTP calls this proactive negotiation: the client describes what it wants in request headers, and the server picks the best match. The most common header is Accept, which lists media types, each with an optional quality value (q) from 0 to 1:
GET /api/reports/42 HTTP/1.1
Accept: application/json, text/csv;q=0.5That reads "JSON, please. CSV is fine if you don't have JSON." The rules come from RFC 9110, Section 12.4:
- No
qmeansq=1. A missing weight is the highest preference. q=0means "not acceptable".Accept: application/json, text/html;q=0explicitly rules HTML out.- Wildcards fill the gaps.
*/*matches anything,text/*matches any text type. If there's no wildcard, anything not listed is unacceptable. - The most specific range wins. In
Accept: text/*;q=0.3, text/plain;q=0.7,text/plaingets 0.7 andtext/htmlgets 0.3. - No header means no preference. A request without
Acceptwill take whatever the server has.
This is why browsers almost never trigger a 406: they always include a wildcard. Chrome's navigation header includes */*;q=0.8, and fetch() with no Accept set sends a bare */*, as the Fetch Standard requires. A request that accepts */* gives the server nothing to reject. Genuine 406s come from API clients and scripts that send a narrow Accept header on purpose.
A Default Representation Is Usually Better
The RFC doesn't just allow you to ignore Accept, it treats doing so as normal.
If a content negotiation header field is present in a request and none of the available representations for the response can be considered acceptable according to it, the origin server can either honor the header field by sending a 406 (Not Acceptable) response or disregard the header field by treating the response as if it is not subject to content negotiation for that request header field. — RFC 9110, Section 12.4.1
Section 12.1 adds that clients can't rely on their preferences being honored, because a server might decide a non-matching response beats a 406. Both options are legitimate. Pick the one that helps the client more:
- Send the default when the client can probably cope. A JSON-only API that gets
Accept: application/xmlcan send JSON. A client that can't parse it sees theContent-Typeat once. One that can (plenty send a stockAcceptheader) is spared a failed request. - Send a 406 when a wrong format would be worse than none. A pipeline asking for CSV that would choke on JSON is better served by a clear refusal and a list of alternatives.
- Honor explicit refusals.
q=0means "not this". The RFC notes thatAccept: */*;q=0lets a client explicitly request a 406 when nothing it prefers exists. If a client goes that far, give it the 406.
The spec builds this in for compression: if none of the client's Accept-Encoding codings is available, the server SHOULD send the response uncompressed unless the client ruled out identity. That's why you'll almost never see a 406 for compression.
406 vs 415 vs 300 vs 400
| Code | Meaning | Use when |
|---|---|---|
| 406 Not Acceptable | No response format matches the client's Accept* headers | The client asked for formats or languages you can't produce, and you choose not to send a default |
| 415 Unsupported Media Type | The request body's format isn't supported | The client sent a Content-Type (or Content-Encoding) this endpoint can't consume |
| 300 Multiple Choices | Several representations fit, and the client should pick | You want the client to choose between alternatives rather than picking for it |
| 400 Bad Request | The request itself is malformed | The syntax is broken, not just the format preferences |
The one to get right is 406 vs 415, which face opposite directions:
- 406 = "I can't send you anything you'll accept." The response is the problem, and the clue is the request's
Acceptheader. - 415 = "I can't read what you sent me." The request body is the problem, and the clue is its
Content-Type.
A JSON-only API returns 415 when a client POSTs XML, and 406 (or just JSON) when a client GETs with Accept: application/xml. Our 415 Unsupported Media Type post covers the request side.
300 is 406's cousin: Section 12.2 names them as the two codes that list alternatives for the client to choose from. A 300 says "several of these suit you"; a 406 says "none of these is what you asked for, but here they are".
Common Causes
- An
Acceptheader that matches no format. A client hardcodesAccept: application/xmlagainst a strict JSON-only API. - An unsupported language.
Accept-Language: eson a server that only has English and German and negotiates strictly. - Other failed negotiation. A missing wildcard, a typo (
application/jsn), orq=0on the only type you offer. - A web application firewall rule. Not negotiation at all. See the next section.
The WAF Red Herring
If you hit a 406 in a browser, or on a form submit on a shared-hosting site, it's probably not about Accept. Browsers always send a wildcard, so something else produced it.
The usual culprit is ModSecurity, the web application firewall module many Apache-based hosts run. It lets the admin choose the status a blocked request gets, and 406 is a long-standing choice, going back to ModSecurity 1.x configs like SecFilterDefaultAction "deny,log,status:406". Hosts still document it: one host's knowledge base says a site that trips its default ModSecurity rules gets "Access denied with code 406" in the logs, or a "Not Acceptable" page.
That page is the confusing part. It's Apache's standard 406 error page, which talks about "an appropriate representation of the requested resource": content-negotiation language for what is really a security block. Typical triggers look like attacks, such as a <script> sample in a blog post or SQL-ish text in a form field.
How to tell them apart:
- Retry with a wildcard.
curl -i -H 'Accept: */*' <url>with the same body. If it still 406s,Acceptisn't the reason. - Look at what varies. If only certain bodies or query strings 406, a rule is matching on content.
- Read the logs. ModSecurity logs the ID of the rule that fired. Hand that to your host, or write a targeted exclusion. Don't switch the whole firewall off.
If you run the firewall, consider denying with 403 instead. A 403 says "refused" plainly, while a 406 sends people off debugging their Accept headers. See our 403 Forbidden post for more on that code.
Returning 406 Correctly
On any platform, three things make a 406 useful: list what's available, send Vary: Accept, and run your other checks first. A missing resource is a 404: there's no format question if there's nothing to format.
Express / Node.js
Express negotiates for you with res.format(). It picks a handler from the Accept header and sets Content-Type to match. With no Accept header, it runs the first handler. If nothing matches and there's no default handler, the result is a 406.
The detail that matters: res.format() doesn't write the 406 itself. It calls next() with a 406 error whose types property lists the formats you offered, and Express's built-in error handler turns that into an HTML error page. Catch it yourself:
import express from "express";
const app = express();
app.get("/api/reports/:id", async (req, res) => {
const report = await getReport(req.params.id);
if (!report) {
return res.status(404).json({ error: "not_found" }); // existence comes first
}
res.format({
"application/json": () => res.json(report),
"text/csv": () => res.send(toCsv(report)),
});
});
// res.format() passes a 406 error to next() when nothing matches
app.use((err, req, res, next) => {
if (err.status === 406) {
return res.status(406).json({
error: "not_acceptable",
message: "This report is available as JSON or CSV.",
available: err.types, // ["application/json", "text/csv"]
});
}
next(err);
});res.format() also sets Vary: Accept on every response, matched or not. To send a default instead of a 406, add a default handler:
res.format({
"application/json": () => res.json(report),
"text/csv": () => res.send(toCsv(report)),
default: () => res.json(report), // ignore Accept and send JSON
});Without res.format(), req.accepts(["json", "csv"]) returns the best match or false, and the Express docs say false means you should respond with 406. Both are built on the accepts package, which uses negotiator for q-values and wildcards.
Next.js App Router
Route Handlers don't negotiate for you. Here's a small matcher that follows the RFC rules above, and a handler that uses it:
// app/api/reports/[id]/route.ts
const OFFERED = ["application/json", "text/csv"];
function preferredType(accept: string | null, offered: string[]): string | null {
if (!accept) return offered[0]; // no Accept header = no preference
const ranges = accept.split(",").map((part) => {
const [range, ...params] = part.split(";").map((s) => s.trim().toLowerCase());
const q = params.find((p) => p.startsWith("q="));
return { range, q: q ? Number(q.slice(2)) : 1 };
});
const specificity = (range: string) =>
range === "*/*" ? 0 : range.endsWith("/*") ? 1 : 2;
let best: { type: string; q: number } | null = null;
for (const type of offered) {
const [main] = type.split("/");
const match = ranges
.filter(({ range }) => range === type || range === `${main}/*` || range === "*/*")
.sort((a, b) => specificity(b.range) - specificity(a.range))[0];
if (match && match.q > 0 && (!best || match.q > best.q)) {
best = { type, q: match.q };
}
}
return best?.type ?? null;
}
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
const report = await getReport(id);
if (!report) {
return Response.json({ error: "not_found" }, { status: 404 });
}
const type = preferredType(request.headers.get("accept"), OFFERED);
const headers = { Vary: "Accept" };
if (!type) {
return Response.json(
{
error: "not_acceptable",
message: "This report is available as JSON or CSV.",
available: [
{ type: "application/json", href: `/api/reports/${id}.json` },
{ type: "text/csv", href: `/api/reports/${id}.csv` },
],
},
{ status: 406, headers },
);
}
if (type === "text/csv") {
return new Response(toCsv(report), {
headers: { ...headers, "Content-Type": "text/csv; charset=utf-8" },
});
}
return Response.json(report, { headers });
}In Next.js 15 and later, route handler params is a Promise, so await it before reading id. The matcher ignores media type parameters like charset, which is fine for a short fixed list. For anything more, use negotiator rather than growing your own parser.
Apache
Apache's mod_negotiation (MultiViews) returns a 406 on its own when every variant of a file is ruled out by the Accept* headers. For languages, ForceLanguagePriority Fallback serves the first language in LanguagePriority instead. The default is Prefer alone, which only breaks ties, so add Fallback yourself:
Options +MultiViews
LanguagePriority en de fr
ForceLanguagePriority Prefer FallbackNow a visitor who only accepts Spanish gets the English page, not an error (mod_negotiation docs).
REST API JSON body
HTTP/1.1 406 Not Acceptable
Content-Type: application/json
Vary: Accept
{
"error": "not_acceptable",
"message": "This report is available as JSON or CSV.",
"available": [
{ "type": "application/json", "href": "/api/reports/42.json" },
{ "type": "text/csv", "href": "/api/reports/42.csv" }
]
}That's the RFC's list of available representations and their identifiers, in a shape a client can act on. One caveat: the RFC says negotiation preferences apply to error responses too, so a JSON body is itself a format the client didn't ask for. There's no format left that it did ask for, so pick something simple.
Vary: Accept and Caching
Any response whose content depends on Accept needs to say so:
Vary: AcceptWithout it, a cache keys the response on the URL alone: one client asks for CSV, the CDN caches it, and the next client asking for JSON gets CSV. Vary adds the listed request headers to the cache key:
To inform cache recipients that they MUST NOT use this response to satisfy a later request unless the later request has the same values for the listed header fields as the original request — RFC 9110, Section 12.5.5
Send it on the 406 too, since that's also a negotiated result. Two practical notes:
Acceptstrings vary a lot. Each browser and HTTP library sends its own, soVary: Acceptcan split one URL into many cache entries. Separate URLs per format (/reports/42.csv) cache better and are easier to debug.- Check your CDN. Not every CDN keys on every
Varyheader by default. Cloudflare, for example, configuresVaryhandling per header through Cache Rules. Confirm a negotiated URL really caches per format.
406 and SEO
A public page should never 406 a crawler. If it does, the page is gone as far as search is concerned: Google doesn't index URLs that return a 4xx, and removes indexed URLs that start returning one.
The usual ways it happens are strict Accept-Language negotiation and an overeager firewall rule. For language versions, serve a default page and point to the others with hreflang rather than refusing. For firewall rules, make sure legitimate crawlers aren't caught.
Common Pitfalls
- Returning 406 when a default would do. If the client could reasonably use your standard format, sending it beats a failed request.
- Confusing 406 with 415. 406 is the response format (
Accept). 415 is the request body format (Content-Type). - A bare 406 with no alternatives. The RFC says a 406 SHOULD list what's available. Without it, the client has to guess.
- Letting Express's default error handler answer.
res.format()passes the 406 tonext(). Catch it, or API clients get an HTML page. - Forgetting
Vary: Accept. Shared caches will serve one client's format to another. - Debugging
Acceptwhen it's a WAF block. A 406 on a browser request is almost certainly a firewall rule. Check the ModSecurity logs first. - Ignoring
q=0.text/html;q=0means "never HTML". A matcher that treats every listed type as acceptable sends exactly what the client ruled out.
Wrapping Up
406 is the server being honest about formats, and the spec lets you decide when honesty helps. The rules of thumb:
- 406 means nothing available matches the client's
Accept*headers, and the server chose not to send a default - Ignoring
Acceptand sending your usual format is explicitly allowed, and often friendlier - Send a 406 when a wrong format would do more harm than none, or the client ruled formats out with
q=0 - A good 406 lists the available formats and where to get them
- 406 is about the response format; 415 is about the request format
- Send
Vary: Accepton negotiated responses, and check your CDN honors it - A 406 on an ordinary browser request is probably a ModSecurity rule, not negotiation
For more, see our pages on 406 Not Acceptable, 415 Unsupported Media Type and 300 Multiple Choices. The request-side mirror of this post is understanding 415 Unsupported Media Type, and you can compare 406 vs 415 side by side.
Related Status Codes
- 400Bad Request
- 401Unauthorized
- 402Payment Required
- 403Forbidden
- 404Not Found
- 405Method Not Allowed
- 406Not Acceptable
- 407Proxy Authentication Required
- 408Request Timeout
- 409Conflict
- 410Gone
- 411Length Required
- 412Precondition Failed
- 413Payload Too Large
- 414URI Too Long
- 415Unsupported Media Type
- 416Range Not Satisfiable
- 417Expectation Failed
- 418I'm a Teapot
- 421Misdirected Request
- 422Unprocessable Entity
- 423Locked
- 424Failed Dependency
- 425Too Early
- 426Upgrade Required
- 428Precondition Required
- 429Too Many Requests
- 431Request Header Fields Too Large
- 451Unavailable For Legal Reasons