401 Unauthorized: What It Means and How to Fix It

Last tested: November 15, 2026 · By Alex

A 401 Unauthorized error means the server wants the request to prove who is making it, and the request either carried no credentials or carried credentials the server did not accept. Despite the name, it is about authentication (who you are), not permission (what you may do). Valid credentials, sent in the form the server expects, make it go away.

On real sites the 401 usually comes from one of a few places: HTTP Basic Auth on a folder or a staging copy, an expired API token, a WordPress REST API call without proper authentication, a security plugin, or a server that quietly drops the Authorization header before PHP sees it. This guide shows how to tell those apart in a few minutes with the response headers and curl, then fix the right layer.

Quick Fix

  • Visitors: check the URL, type the username and password by hand instead of using autofill, and try a private window. If you were never given a login, the page is not meant to be public.
  • Site owners: run curl -I on the URL and read the WWW-Authenticate header. Basic points to password protection, Bearer to a token, no header usually to application or plugin code.
  • Test the same credentials with curl -u. If curl gets 200 and the browser does not, the browser is sending something old.
  • For WordPress API clients, create a fresh Application Password and make sure the server passes the Authorization header to PHP.
  • Purge the CDN and page cache if the cause is fixed but the 401 is still shown.

What 401 Unauthorized Means

Diagram of a 401 Unauthorized exchange: the browser requests a protected page, the server answers 401 with a WWW-Authenticate header, the client retries with an Authorization header, and the server returns 200 only if the credentials are accepted

HTTP authentication is a short conversation. The client asks for a resource, the server answers 401 and names the scheme it accepts in a WWW-Authenticate header, the client repeats the request with an Authorization header, and the server either serves the page or answers 401 again. The HTTP specification requires a 401 response to include at least one WWW-Authenticate challenge, so its presence and content are your first clue.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Staging"

Read the WWW-Authenticate header

  • Basic: a username and password prompt set up in Apache, NGINX, a hosting panel or a proxy. Browsers show their native login popup for it.
  • Bearer: an API expects a token. Many APIs add error="invalid_token" and a short description when the token is expired or malformed.
  • Negotiate or NTLM: Windows integrated authentication, usually on IIS intranet sites. A 401 from these often means the browser is not allowed to send domain credentials to that host.
  • No header at all: an application, plugin or API returned 401 by itself. The response body, often JSON, tells you more than the headers.

Authentication, not permission

A 401 says the server does not know who you are yet. Once it does know and still refuses, the correct answer is 403. That difference decides where you look: a 401 sends you to credentials, tokens and headers, while a 403 sends you to roles, file permissions, firewall rules and IP blocks.

401 vs 403 vs 407

CodeMeaningChallenge headerWill logging in help?
401 UnauthorizedNo credentials, or credentials rejected by the serverWWW-AuthenticateYes, with valid credentials in the right format
403 ForbiddenThe server understood the request and refuses itNone requiredUsually not; a rule, role or permission blocks access
407 Proxy Authentication RequiredA proxy between you and the site wants credentialsProxy-AuthenticateYes, but for the proxy, sent in Proxy-Authorization

A 407 almost always comes from a company or school network, not from the website, so the site owner cannot fix it. Two neighbours are also easy to mix up: a 400 Bad Request means the request itself is malformed, and 429 Too Many Requests means the client is rate limited, even with valid credentials.

If You Are a Visitor

  • Check that you have the right address. A login prompt on a URL with staging, dev or test in it is expected.
  • Type the credentials manually. Watch Caps Lock and the keyboard layout, and remember the username is often case sensitive.
  • Use a private window. Browsers remember Basic Auth credentials until every window is closed, so a wrong saved password keeps being resent.
  • Clear cookies for the site if the 401 appears after logging out or changing a password.
  • If you reach the site through a VPN or a work network and see a proxy login instead, the 407 belongs to the network administrator.

If none of that helps and you think the page should be public, tell the site owner the exact URL and the time. A 401 on a public page is a configuration mistake on their side.

If You Own the Site: Find Which Layer Sends the 401

Several systems can produce the same status code: the CDN or hosting edge, the web server, PHP or the application, and remote APIs your site calls. Before changing anything, identify the sender:

  • A WWW-Authenticate: Basic header with a realm you recognise points to your own Apache, NGINX or panel protection.
  • A JSON body with a code field points to the application. WordPress REST errors look like rest_not_logged_in or rest_forbidden.
  • Headers such as cf-ray or a custom branded error page mean the request passed through a CDN; test the origin directly to see whether the edge or the server answered.
  • A 401 that only appears in a plugin’s log while visitors see a normal page comes from an external API the plugin calls with an outdated key.

Test the 401 with curl

Terminal testing a 401 Unauthorized error with curl: a request without credentials returns 401 and WWW-Authenticate Basic, the same request with the -u option returns HTTP 200

curl shows the raw status and headers without browser caches, saved passwords or extensions. Start with the headers only:

curl -I https://example.com/protected/

Some applications answer a HEAD request differently from a normal one, so repeat with -i, which sends a GET and prints headers and body. Then add credentials:

# Basic Auth (quote the pair if the password has special characters)
curl -i -u 'alex:S3cret!pass' https://example.com/protected/

# Bearer token
curl -i -H 'Authorization: Bearer YOUR_TOKEN' https://api.example.com/v1/me

# See exactly what is sent and received
curl -v -u 'alex:S3cret!pass' https://example.com/protected/ -o /dev/null

Reading the result

  • curl gets 200, the browser gets 401: the credentials are fine; the browser is sending an old password, an old cookie or nothing at all.
  • Both get 401 and the header says Basic: the user is missing from the password file, the password is wrong, or the server cannot read the file.
  • Both get 401 with no WWW-Authenticate header: the application rejects the request. Read the body and the application log.
  • The same credentials work on another server or locally: suspect a stripped Authorization header (cause 4 below).

Causes and Fixes

1. Wrong, old or cached credentials

Most 401s are simply the wrong password, the right password for a different environment, or a password manager filling an entry saved before the last change. Basic Auth usernames cannot contain a colon, and a password with spaces or symbols needs quoting on the command line. Fix the saved entry, close every browser window to drop the cached credentials, and sign in again.

2. Basic Auth on Apache with .htpasswd

A protected folder on Apache or LiteSpeed usually has a block like this in its .htaccess or virtual host:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/username/.htpasswds/.htpasswd
Require valid-user

Correct credentials still fail when the user is not in the file, when the file cannot be read by the web server user, or when AuthUserFile is relative: Apache resolves a relative path from its ServerRoot, not from the folder, so always use an absolute path. Keep the password file outside the public web root. The Apache error log names the problem with lines such as AH01617: user alex: authentication failure (wrong password) or AH01618: user alex not found.

# add or reset a user (only use -c when creating a new file; it overwrites the old one)
htpasswd /home/username/.htpasswds/.htpasswd alex

# the web server must be able to read it
ls -l /home/username/.htpasswds/.htpasswd

If Apache answers with a 500 Internal Server Error as soon as you add these lines, the server does not allow authentication directives in .htaccess (AllowOverride without AuthConfig), and the block has to go into the server config or the hosting panel’s directory protection instead.

3. Basic Auth on NGINX

NGINX uses auth_basic with a password file in the same format. When you protect /wp-admin/, leave admin-ajax.php open, because front-end features call it for logged-out visitors:

location /wp-admin/ {
    auth_basic           "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

location = /wp-admin/admin-ajax.php {
    auth_basic off;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
sudo htpasswd -c /etc/nginx/.htpasswd alex   # apache2-utils on Debian and Ubuntu
sudo nginx -t && sudo systemctl reload nginx

Adjust the PHP-FPM socket to your version. NGINX relies on the system for some hash types, so if users created with bcrypt (htpasswd -B) never get in, recreate them with the default hash and check /var/log/nginx/error.log for the reason.

4. The Authorization header is stripped before PHP

When PHP runs as CGI or FastCGI behind Apache, Apache does not pass the Authorization header to scripts by default. Credentials reach the server, PHP never sees them, and the application answers 401. Confirm it with a temporary file:

<?php
// auth-test.php - delete right after testing
var_dump($_SERVER['HTTP_AUTHORIZATION'] ?? 'missing');
var_dump($_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? 'missing');
var_dump($_SERVER['PHP_AUTH_USER'] ?? 'missing');
curl -u 'alex:test' https://example.com/auth-test.php

If every value says missing, the header is lost. Since WordPress 5.6 the default rewrite rules include a line that copies it into an environment variable, so saving Settings > Permalinks often restores it. Site Health reports the same issue as a missing authorization header. You can also add it by hand above the WordPress block:

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# or, on Apache 2.4.13 and newer
CGIPassAuth On

On NGINX with PHP-FPM, the stock fastcgi_params file does not handle this header specially, and PHP normally receives it. If a custom config filters headers, add fastcgi_param HTTP_AUTHORIZATION $http_authorization;. Behind a reverse proxy, check that no layer clears it with proxy_set_header Authorization "";.

5. WordPress REST API and Application Passwords

The REST API treats a request without valid authentication as a logged-out visitor. Public routes still work; protected ones answer 401 with codes such as rest_not_logged_in or rest_forbidden. For scripts, apps and integrations, use an Application Password, created under Users > Profile > Application Passwords:

curl -i -u 'alex:abcd EFGH ijkl MNOP qrst UVWX' https://example.com/wp-json/wp/v2/users/me

A few details trip people up. Application Passwords only work over HTTPS unless the site is marked as a local environment. They do not replace the normal login password, and the normal password does not work for REST Basic Auth. Some security and two-factor plugins switch the feature off entirely, which removes the section from the profile screen. Custom JavaScript that relies on the login cookie must send an X-WP-Nonce header; without it the request is treated as logged out. An invalid nonce returns a 403 (rest_cookie_invalid_nonce), not a 401, so reload the page if a tab was left open for a long time. The WordPress REST API error guide covers the non-authentication failures on the same routes.

6. Expired or malformed tokens

APIs that use bearer tokens answer 401 when the token has expired, was revoked, belongs to another environment, or is sent in the wrong format. The header must be exactly Authorization: Bearer TOKEN with one space. For a JWT, decode the middle part and compare exp with the current Unix time:

echo 'PAYLOAD_PART_OF_JWT' | base64 -d 2>/dev/null; echo; date +%s

A smaller exp means it expired. Generate a new token, then update it everywhere it is stored: environment variables, plugin settings and CI secrets. A server clock that is several minutes off can also make fresh tokens look expired or not yet valid. Very large tokens cause a different failure, 431 Request Header Fields Too Large.

7. Security plugins and login protection

Plugins that restrict the REST API to logged-in users, hide the login page or add brute-force protection can turn normal requests into 401s. Typical symptoms are contact forms, search or a headless front end failing only for logged-out visitors. Allow the routes your site needs in the plugin settings. If you cannot reach wp-admin, rename the plugin’s folder in wp-content/plugins over SFTP to disable it, test, and rename it back.

8. Hosting and CDN password protection

Hosts often protect staging copies with Basic Auth, and control panels have a Directory Privacy or Password Protect Directories tool that writes the rules for you. A prompt you did not set up usually comes from there, and a protected parent folder also covers everything inside it. On a CDN, a login page or a 401 can come from an access-control product, a Worker or a custom firewall response. Test the origin while skipping the CDN:

curl -i --resolve example.com:443:ORIGIN_IP https://example.com/protected/

If the origin answers normally, change the rule at the edge. If it answers 401 too, the cause is on your server. An edge page that says access was denied by a firewall rule is a block, not a login request; see Cloudflare Error 1020.

9. A cached 401

If the cause is fixed but visitors still see the error, a cache may be serving the old response. Headers such as cf-cache-status: HIT or x-litespeed-cache: hit on a 401 confirm it. Purge the CDN and page cache, and make sure cache rules bypass /wp-admin/, /wp-json/ and requests with login cookies.

Step-by-Step Fix for a 401 Unauthorized Error

Five-step fix path for a 401 Unauthorized error: read the WWW-Authenticate header, test credentials with curl, check Basic Auth files, pass the Authorization header to PHP, and review WordPress application passwords and security plugins
  1. Read the challenge. curl -I and note the WWW-Authenticate scheme and any JSON error code.
  2. Test the credentials with curl -u or a bearer header to separate browser problems from server problems.
  3. Check Basic Auth: the user exists in the password file, the path is absolute and readable, and the error log agrees.
  4. Confirm PHP receives the Authorization header with a test file, then fix it with the rewrite rule or CGIPassAuth.
  5. Review the application layer: Application Passwords, nonces, tokens, security plugins and CDN rules, then purge caches.

When WordPress Itself Gets a 401

WordPress calls its own site for scheduled tasks, Site Health checks and some editor features. If you protect the whole site with Basic Auth, those loopback requests get a 401 too, because WordPress does not know the password. Exclude wp-cron.php and admin-ajax.php from the protection, or run cron from the server instead; the guide to WordPress missed schedule shows both options. If the login form keeps sending you back without any 401, that is a cookie problem, covered in WordPress login redirect loop.

Prevention

  • Use Application Passwords or scoped API tokens for integrations, one per app, so you can revoke a single one.
  • Store tokens in environment variables or a secrets manager and record when they expire.
  • Document every Basic Auth setup: which paths, which password file, and who has access.
  • After a migration or a PHP handler change, test an authenticated REST request at once, because header handling often changes between hosts.
  • Never cache 401 responses or authenticated pages at the CDN.
  • Keep staging protection separate from production so a copied rule does not lock out real visitors.

For other client errors, see 405 Method Not Allowed and 404 Not Found, or start from the step-by-step website errors hub.

What does 401 Unauthorized mean?

The server needs authentication for the resource, and the request had no credentials or had credentials the server rejected. The response normally includes a WWW-Authenticate header that names the expected scheme.

What is the difference between 401 and 403?

A 401 means the server does not know who you are yet, so valid credentials can fix it. A 403 means the server refuses the request even when it knows who you are, so logging in again will not help.

Why does the WordPress REST API return 401 with correct credentials?

Often the server strips the Authorization header before it reaches PHP. Save the permalinks to restore the rewrite rule, or add CGIPassAuth On on Apache, and use an Application Password over HTTPS.

How do I remove the password popup from my site?

The popup comes from HTTP Basic Auth. Remove or fix the AuthType Basic block in .htaccess, the auth_basic lines in NGINX, or the directory password protection in your hosting panel.

What is a 407 error and is it the same as 401?

It is similar, but a 407 Proxy Authentication Required comes from a proxy between you and the website, usually on a company network. The network administrator fixes it, not the site owner.

Can a cache keep showing a 401 after the fix?

Yes. If a CDN or page cache stored the 401 response, visitors keep seeing it. Purge the caches and make sure admin pages, the REST API and logged-in requests are never cached.

Leave a Comment