More
More
401 Unauthorized
Authentication is needed and was missing or wrong.
- Code
401- Reason phrase
- Unauthorized
- Class
- 4xx Client error
- Defined in
- RFC 9110 section 15.5.2
- Cacheable by default
- No
What it means
Client error: the problem lies with the request. Repeating it unchanged will normally fail again.
When a server should send it. When the request lacks valid credentials and could succeed with them. The response must include a WWW-Authenticate header naming the scheme, such as Basic or Bearer. If the user is known but not allowed, send 403 instead.
Common causes. No login, an expired session, a missing or invalid API key or token.
What to do. Sign in again or refresh the token. Despite the name it means unauthenticated; for a valid login without permission the code is 403.
How clients and crawlers treat it
Browsers and HTTP clients. With WWW-Authenticate: Basic or Digest, browsers show their own username and password prompt. With Bearer or a custom scheme they show the page body, and API clients typically refresh the token and retry once.
Google Search. Like every 4xx except 429, it tells Google the content does not exist: an indexed URL is removed from the index, and a new one is not processed. Crawl frequency for the URL gradually drops. Google advises against using 401 or 403 to slow Googlebot down; use 429 or 503 for that. Source: Google Search Central, How HTTP status codes, and network and DNS errors affect Google Search.
Caching. Not cacheable by default (RFC 9110 section 15.1 does not list it). A cache stores it only when the response says so with Cache-Control or Expires.
Example response
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token"
Content-Type: application/json
{"status": 401, "title": "Unauthorized"}
How to send 401
location /example {
add_header WWW-Authenticate 'Bearer realm="api"' always;
return 401;
}
Header always set WWW-Authenticate "Bearer realm=\"api\"" RewriteEngine On RewriteRule ^example$ - [R=401,L]
header('WWW-Authenticate: Bearer realm="api"');
http_response_code(401);
echo 'Unauthorized';
exit;
res.writeHead(401, { 'WWW-Authenticate': 'Bearer realm="api"', 'Content-Type': 'text/plain' });
res.end('Unauthorized');
# in a view function
return 'Unauthorized', 401, {'WWW-Authenticate': 'Bearer realm="api"'}
Change the paths to suit. In nginx, add_header needs always to apply to error responses.
Related codes
- 403ForbiddenThe server understood the request but refuses it.
- 407Proxy Authentication RequiredLike 401, but the proxy in between needs the login.
- 404Not FoundNothing exists at this address, or the server will not say that it does.
All status codes · All 4xx codes
Names and numbers from the IANA HTTP Status Code Registry. Google Search behaviour as documented by Google Search Central.