Skip to content
Proxy fundamentals

HTTP 401 vs 403 vs 407: what each code means

401 asks for credentials, 403 refuses with or without them, 407 is your proxy asking. Real curl, requests, httpx and Node output for each.

On this page 6 sections
  1. 401 vs 403 vs 407 at a glance
  2. What we ran
  3. The three responses, header by header
  4. Differences that bite in practice
  5. A proxy can send 403 as well
  6. Over HTTPS, the proxy’s answer never becomes a status code
  7. Apache answers a valid user with 401, not 403
  8. Many APIs send 401 without the header the RFC requires
  9. 403 and 404 trade places on purpose
  10. The wrong flag turns a proxy password into a 407
  11. Frameworks pick the code for you
  12. When each one is the right choice
  13. Finding out which hop refused you

A 401 means the server wants credentials it did not get or did not accept, and it has to say how to send them. A 403 means the server understood the request and will not carry it out. A 407 is a proxy’s 401: the hop between you and the site wants its own credentials first. The number is the weaker clue. The header that arrives with it is the strong one. A 401 must carry WWW-Authenticate, a 407 must carry Proxy-Authenticate, and a 403 needs neither.

Every response quoted on this page came from real software on one machine: Apache httpd playing the website, Squid playing the proxy, and curl, Python requests, httpx and Node.js as clients. Versions and the exact configuration are listed further down.

401 vs 403 vs 407 at a glance

401 Unauthorized 403 Forbidden 407 Proxy Authentication Required
Who sends it The origin server The origin, or a proxy enforcing its own policy A proxy
What it says No valid credentials for this resource Understood, and refused No valid credentials for this proxy
Header the response must carry WWW-Authenticate None Proxy-Authenticate
Header your client answers with Authorization None defined Proxy-Authorization
Send the same request again? Only with new credentials RFC 9110: SHOULD NOT with the same credentials Only with new proxy credentials
What to change The site login, token or API key Your permissions, or whatever policy blocks you Proxy username, password or allowlisted address
curl flag involved -u user:pass or an Authorization header None fixes it -U user:pass, or credentials inside the -x URL
HTTPS through a proxy, curl reports http_code=401 http_connect=200 From the site: http_code=403 http_connect=200. From the proxy: http_code=000 http_connect=403 http_code=000 http_connect=407, exit 56

Two rows do most of the work. If the response names a scheme in Proxy-Authenticate, fix the proxy settings and leave the site alone. If it names one in WWW-Authenticate, the proxy did its job and the site wants a login. A 403 with neither header is a decision. Sending the identical request again will not change it.

What we ran

The bench ran on loopback on 21 October 2026, on macOS 26 (Darwin 25.6). Nothing left the machine except the API survey further down.

Role Software Version
Origin server Apache httpd, mod_auth_basic and mod_authz_core 2.4.67
Forward proxy Squid with basic_ncsa_auth 6.13
Client curl (SecureTransport, LibreSSL 3.3.6) 8.7.1
Client Python requests on urllib3 2.3.0, Python 3.9.6 2.32.3
Client httpx 0.27.2
Client Node.js built-in fetch (bundled undici 7.10.0) 24.2.0
Client undici package, fetch with ProxyAgent 8.10.2

Apache served four directories. One was open, one sat behind Basic auth for any valid user, one only the user alice could read, and one was denied to everyone. Squid demanded Basic proxy credentials, then refused one URL path and every tunnel to port 443 by policy. These are the lines that decide each status code, with paths shortened:

# httpd.conf
<Directory "docroot/basic">
  AuthType Basic
  AuthName "origin-area"
  AuthUserFile origin.htpasswd
  Require valid-user
</Directory>
<Directory "docroot/alice-only">
  AuthType Basic
  AuthName "origin-area"
  AuthUserFile origin.htpasswd
  Require user alice
</Directory>
<Directory "docroot/forbidden">
  Require all denied
</Directory>

# squid.conf
auth_param basic program /opt/homebrew/opt/squid/libexec/basic_ncsa_auth proxy.htpasswd
auth_param basic realm test-proxy
acl authed proxy_auth REQUIRED
acl CONNECT method CONNECT
acl tunnel_ports port 28443 443
acl proxy_blocked urlpath_regex ^/forbidden-by-proxy
acl blocked_tunnel port 443
http_access deny !authed
http_access deny proxy_blocked
http_access deny CONNECT blocked_tunnel
http_access deny CONNECT !tunnel_ports
http_access allow authed
http_access deny all

The three responses, header by header

No credentials, one request each. The origin listens on port 28401 and the proxy on 28407.

$ curl -sS -D - -o /dev/null http://127.0.0.1:28401/basic/ok.txt
HTTP/1.1 401 Unauthorized
Date: Wed, 21 Oct 2026 19:27:14 GMT
Server: Apache/2.4.67 (Unix) LibreSSL/3.3.6
WWW-Authenticate: Basic realm="origin-area"
Content-Length: 421
Content-Type: text/html; charset=iso-8859-1

$ curl -sS -D - -o /dev/null http://127.0.0.1:28401/forbidden/ok.txt
HTTP/1.1 403 Forbidden
Date: Wed, 21 Oct 2026 19:27:14 GMT
Server: Apache/2.4.67 (Unix) LibreSSL/3.3.6
Content-Length: 239
Content-Type: text/html; charset=iso-8859-1

$ curl -sS -D - -o /dev/null -x http://127.0.0.1:28407 http://127.0.0.1:28401/open/ok.txt
HTTP/1.1 407 Proxy Authentication Required
Server: squid/6.13
Mime-Version: 1.0
Date: Wed, 21 Oct 2026 19:27:15 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 3576
X-Squid-Error: ERR_CACHE_ACCESS_DENIED 0
Vary: Accept-Language
Content-Language: en
Proxy-Authenticate: Basic realm="test-proxy"
Cache-Status: squid-rig
Via: 1.1 squid-rig (squid/6.13)
Connection: keep-alive

RFC 9110 makes the challenge headers mandatory. A server generating a 401 MUST send WWW-Authenticate, and a proxy MUST send Proxy-Authenticate in every 407 it generates. The 403 has no such rule. It may explain itself in the body, and Apache’s body says only “You don’t have permission to access this resource.”

The client answers each challenge with a different header, which is why one request can carry two sets of credentials at once. Proxy credentials travel in Proxy-Authorization, and the RFC says the first proxy that asked for them consumes them. Site credentials travel in Authorization and go all the way to the origin. We set Apache’s access log to print both headers, and Squid did exactly what the RFC describes:

$ curl -sS -o /dev/null -w '%{http_code}\n' \
    -x http://puser:proxy-pass@127.0.0.1:28407 \
    -u alice:origin-pass http://127.0.0.1:28401/basic/ok.txt
200

# Apache access log line for that request
127.0.0.1 "GET /basic/ok.txt HTTP/1.1" 200 Authorization=[Basic YWxpY2U6b3JpZ2luLXBhc3M=] Proxy-Authorization=[-] Via=[1.1 squid-rig (squid/6.13)]

The proxy password never reached the site. The reverse is not true over plain HTTP: the site’s Authorization header passed through Squid in readable form. Over HTTPS the same header sits inside the TLS tunnel, and Squid’s log for those requests records only CONNECT 127.0.0.1:28443 puser. A proxy that intercepts TLS would be a different case. For the general mechanics of proxy authentication and the forward proxy role, see the glossary.

Differences that bite in practice

A proxy can send 403 as well

Our 403 vs 407 vs 429 guide works from a shortcut: 407 comes from your proxy, 403 from the destination. For anti-bot blocks that holds most of the time. It is not a protocol rule. A proxy with an access policy refuses with 403 like any other server, and Squid 6.13 did so the moment an authenticated user asked for a path its rules deny:

$ curl -sS -D - -o /dev/null -x http://puser:proxy-pass@127.0.0.1:28407 \
    http://127.0.0.1:28401/forbidden-by-proxy/x
HTTP/1.1 403 Forbidden
Server: squid/6.13
Mime-Version: 1.0
Date: Wed, 21 Oct 2026 19:27:15 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 3642
X-Squid-Error: ERR_ACCESS_DENIED 0
Vary: Accept-Language
Content-Language: en
Cache-Status: squid-rig
Via: 1.1 squid-rig (squid/6.13)
Connection: keep-alive

Do not use the Via header to decide who wrote a response. Squid stamped Via: 1.1 squid-rig (squid/6.13) on its own 403 and on the origin’s 401 that it relayed. What separates them is the Server header, Squid’s X-Squid-Error, and the page title: “ERROR: The requested URL could not be retrieved” from Squid, “403 Forbidden” from Apache.

The proxy’s own log gives the shortest answer, because it records whether it refused the request or passed a refusal along:

TCP_DENIED/407 3974 GET http://127.0.0.1:28401/open/ok.txt - HIER_NONE/- text/html
TCP_MISS/401 741 GET http://127.0.0.1:28401/basic/ok.txt puser HIER_DIRECT/127.0.0.1 text/html
TCP_DENIED/403 3968 GET http://127.0.0.1:28401/forbidden-by-proxy/x puser HIER_NONE/- text/html

In Squid’s log format, DENIED means its access controls refused the request, and HIER_NONE means there is no upstream hop to report. TCP_MISS with HIER_DIRECT means the response was fetched from the origin server.

Over HTTPS, the proxy’s answer never becomes a status code

For an https:// URL the client first sends CONNECT host:port to the proxy and waits for a 200 before it starts TLS. A 407 or a 403 at that point answers the CONNECT, not your GET. curl keeps the two apart in separate write-out variables:

$ curl -sS -k -o /dev/null -w 'http_code=%{http_code} http_connect=%{http_connect}\n' \
    -x http://127.0.0.1:28407 https://127.0.0.1:28443/open/ok.txt
curl: (56) CONNECT tunnel failed, response 407
http_code=000 http_connect=407

$ curl -sS -k -o /dev/null -w 'http_code=%{http_code} http_connect=%{http_connect}\n' \
    -x http://puser:proxy-pass@127.0.0.1:28407 https://127.0.0.1:443/
curl: (56) CONNECT tunnel failed, response 403
http_code=000 http_connect=403

$ curl -sS -k -o /dev/null -w 'http_code=%{http_code} http_connect=%{http_connect}\n' \
    -x http://puser:proxy-pass@127.0.0.1:28407 https://127.0.0.1:28443/basic/ok.txt
http_code=401 http_connect=200

A monitoring script that logs only %{http_code} writes 000 for a wrong proxy password. Log %{http_connect} next to it. The exit code does not settle it either: 56 is curl’s generic “Failure with receiving network data”.

Libraries go one step further and turn the proxy’s answer into an exception. Same bench, same proxy, every client:

Client 407, http:// target 407 on CONNECT, https:// target 403 on CONNECT Origin 401 inside the tunnel
curl 8.7.1 http_code 407 exit 56, CONNECT tunnel failed, response 407 exit 56, CONNECT tunnel failed, response 403 http_code 401
requests 2.32.3 r.status_code 407 raises ProxyError: Tunnel connection failed: 407 Proxy Authentication Required raises ProxyError: Tunnel connection failed: 403 Forbidden r.status_code 401
httpx 0.27.2 r.status_code 407 raises httpx.ProxyError('407 Proxy Authentication Required') raises httpx.ProxyError('403 Forbidden') r.status_code 401
Node 24.2.0 fetch, NODE_USE_ENV_PROXY=1 rejects fetch failed; inner cause Proxy response (407) !== 200 when HTTP Tunneling same as the http:// case rejects fetch failed; inner cause Proxy response (403) !== 200 when HTTP Tunneling r.status 401
undici 8.10.2 fetch + ProxyAgent rejects fetch failed; cause InvalidArgumentError: Proxy Authentication Required (407) rejects fetch failed; cause Request was cancelled., inner cause Proxy response (407) !== 200 when HTTP Tunneling rejects fetch failed; cause Request was cancelled., inner cause Proxy response (403) !== 200 when HTTP Tunneling r.status 401

A status_code == 407 check never fires for HTTPS targets in requests or httpx, and it never fired at all with Node’s fetch. Catch the proxy exception and read the code out of its message. Node buries it two levels down, in err.cause.cause.message.

Two more details from the Node run. Node 24.2.0 refused the --use-env-proxy flag with node: bad option: --use-env-proxy, while the NODE_USE_ENV_PROXY=1 environment variable worked. Node’s CLI documentation lists the variable as added in v24.0.0 and the flag in v24.5.0. And Node’s built-in client opened a CONNECT tunnel even for the http:// URL, which Squid logged as CONNECT 127.0.0.1:28401. The undici 8.10.2 ProxyAgent sent that same URL as a plain GET. Client setup is covered in proxies in Python with requests and httpx and proxies in Node.js.

Apache answers a valid user with 401, not 403

Bob has the right password but is not on the Require user alice list. The textbook answer is 403. Apache 2.4.67 sent him the same 401 and the same challenge it sends a stranger:

$ curl -sS -D - -o /dev/null -u bob:origin-pass http://127.0.0.1:28401/alice-only/ok.txt
HTTP/1.1 401 Unauthorized
Date: Wed, 21 Oct 2026 19:27:14 GMT
Server: Apache/2.4.67 (Unix) LibreSSL/3.3.6
WWW-Authenticate: Basic realm="origin-area"
Content-Length: 421
Content-Type: text/html; charset=iso-8859-1

Only the error log tells the failures apart. A wrong password logged AH01617: user alice: authentication failure for "/basic/ok.txt": Password Mismatch. Bob logged AH01631: user bob: authorization failure for "/alice-only/ok.txt". The Require all denied directory, the one that actually produced a 403, logged AH01630: client denied by server configuration.

This is allowed. RFC 9110 says a 401 sent in reply to a request that carried credentials means authorization was refused for those credentials. Apache documents the default and what changing it costs. Its AuthzSendForbiddenOnFailure On directive switches the answer to 403, and the manual warns that doing so reveals to an attacker that a guessed password was right. We turned it on:

$ curl -sS -D - -o /dev/null -u bob:origin-pass http://127.0.0.1:28401/alice-only/ok.txt
HTTP/1.1 403 Forbidden
Date: Wed, 21 Oct 2026 19:34:28 GMT
Server: Apache/2.4.67 (Unix) LibreSSL/3.3.6
Content-Length: 239
Content-Type: text/html; charset=iso-8859-1

$ curl -sS -o /dev/null -w "%{http_code}\n" -u bob:wrong http://127.0.0.1:28401/alice-only/ok.txt
401

With the directive on, the status code becomes a password oracle: 403 for a correct password, 401 for a wrong one. That trade-off, a clearer message for real users against a free confirmation for anyone guessing, is the actual 401 versus 403 decision for a login-protected area.

Many APIs send 401 without the header the RFC requires

We called 16 public API endpoints that need an account. Each got one GET from curl 8.7.1 with no credentials, in two passes on 21 October 2026 (19:28 and 19:29 UTC). Both passes returned identical status codes and challenge headers. Heroku answered 400 with "id":"missing_version" until it received the Accept: application/vnd.heroku+json; version=3 header its API requires, then 401, and the 401 is what we count.

16 public API endpoints called with no credentials, 21 October 2026 Drawn from the table below.
16 public API endpoints called with no credentials, 21 October 2026. Bar chart of Endpoints by Response.4 rows, drawn from the table that follows this chart.401 with WWW-Authenticate401 with WWW-Authenticate: 55401 without WWW-Authenticate401 without WWW-Authenticate: 88403403: 22200 with an error in the body200 with an error in the body: 1102468 endpoints16 public API endpoints called with no credentials, 21 October 2026. Bar chart of Endpoints by Response.4 rows, drawn from the table that follows this chart.401 withWWW-Authenticate401 with WWW-Authenticate: 55401 withoutWWW-Authenticate401 without WWW-Authenticate: 88403403: 22200 with an error in thebody200 with an error in the body: 110510 endpoints
Response Endpoints
401 with WWW-Authenticate 5
401 without WWW-Authenticate 8
403 2
200 with an error in the body 1
Endpoint Status WWW-Authenticate
registry-1.docker.io/v2/ 401 Bearer realm="https://auth.docker.io/token",service="registry.docker.io"
ghcr.io/v2/ 401 Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:user/image:pull"
api.stripe.com/v1/charges 401 Basic realm="Stripe"
api.openai.com/v1/models 401 Bearer realm="OpenAI API"
graph.microsoft.com/v1.0/me 401 Bearer realm="", authorization_uri="https://login.microsoftonline.com/common/oauth2/authorize", client_id=... (cut by us)
api.github.com/user 401 not sent
gitlab.com/api/v4/user 401 not sent
api.anthropic.com/v1/models 401 not sent
api.digitalocean.com/v2/account 401 not sent
api.heroku.com/account 401 not sent
discord.com/api/v10/users/@me 401 not sent
registry.npmjs.org/-/whoami 401 not sent
api.x.com/2/users/me 401 not sent
www.googleapis.com/drive/v3/files 403 not sent
api.cloudflare.com/client/v4/user 403 not sent
slack.com/api/auth.test 200 not sent

Eight of the thirteen 401s arrived without WWW-Authenticate. A client that waits for a challenge before sending credentials would never send them to most of this list. Google Drive and Cloudflare chose 403 for a request that carried no credentials at all, with bodies that read “Method doesn’t allow unregistered callers” and “Missing X-Auth-Email header”. Slack returned 200 with {"ok":false,"error":"not_authed"}, which no status check will catch.

The endpoints that do send the header show what it is for. The two container registries put a token endpoint in realm, and the registry token specification has the client fetch a token from that URL and retry. Stripe names Basic. Microsoft Graph points at its sign-in authority in authorization_uri. For a client, the lesson is to treat any 401 as “credentials missing or rejected”, challenge or not. For a server, send the header anyway. It costs one line and it is the only part of the response that tells a generic client what to do next.

403 and 404 trade places on purpose

RFC 9110 lets an origin that wants to hide a forbidden resource answer 404 instead of 403. GitHub does this. Its REST API troubleshooting page says an unauthenticated request for a private resource gets 404, to avoid confirming that a private repository exists. Amazon S3 goes the other way. A request for an object that does not exist returns 404 only if the caller holds s3:ListBucket on the bucket, and 403 without it. A 403 from S3 can mean “missing”, and a 404 from GitHub can mean “not logged in”. Check the credentials before you conclude a resource is gone.

The wrong flag turns a proxy password into a 407

curl’s -u sends credentials to the site. -U, the short form of --proxy-user, sends them to the proxy. Swap them and the proxy sees nothing:

$ curl -sS -o /dev/null -w "%{http_code}\n" -u puser:proxy-pass -x http://127.0.0.1:28407 http://127.0.0.1:28401/open/ok.txt
407
$ curl -sS -o /dev/null -w "%{http_code}\n" -U puser:proxy-pass -x http://127.0.0.1:28407 http://127.0.0.1:28401/open/ok.txt
200

requests has the same split. Its auth= argument is for the site, so proxy credentials passed there produced Tunnel connection failed: 407 Proxy Authentication Required on an HTTPS URL. Proxy credentials belong in the proxy URL, as in http://user:pass@gw.example.net:8000, or in HTTPS_PROXY; see HTTP_PROXY, HTTPS_PROXY and NO_PROXY explained and how to use a proxy with curl. A plain wrong password gets the same answer: puser:wrong returned 407 on our bench, indistinguishable from sending nothing.

Frameworks pick the code for you

Django REST Framework decides by the first authentication class on the view. Because a 401 must carry WWW-Authenticate, classes that can name a scheme produce 401: BasicAuthentication sends Basic realm="api" and TokenAuthentication sends Token. SessionAuthentication has no scheme to name, so an unauthenticated request gets 403. An authenticated user without permission gets 403 under every class.

OAuth bearer APIs follow RFC 6750. An expired, revoked or malformed token is invalid_token with 401, and the client may fetch a new token and retry. A valid token without the needed scope is insufficient_scope with 403. A malformed request is invalid_request with 400.

When each one is the right choice

If you run the server:

  • Send 401 when the request has no credentials, or credentials that fail to verify, including an expired token. Include a WWW-Authenticate challenge that names the scheme.
  • Send 403 when you know who the caller is and they lack permission, or when identity is beside the point: an IP rule, a failed CSRF check, a file nobody may read. Clients are told not to retry it unchanged, so make the body say why.
  • Send 404 instead of 403 when admitting the resource exists would leak something.
  • Keep 401 for “right user, wrong area” when password guessing worries you more than user confusion. That is Apache’s default, and the risk its manual warns about if you change it. Switch to 403 when a clear message to real users matters more.
  • Send 407 only from a proxy. An origin that wants credentials uses 401, even with a proxy in front of it.

If you are the client:

  • 407: fix the proxy side, meaning the username, password, port or allowlisted address. The target site is not involved. If your provider authenticates by source address, check whether your egress changed; see IP whitelisting.
  • 401: the proxy worked. Fix the site’s credentials or token.
  • 403: find out who sent it before changing anything. If it arrived on the CONNECT, or Server names your proxy, it is the proxy’s policy. If it came from the site, different credentials may help and the same ones will not. Block pages from anti-bot systems are a separate problem, worked through in the 403, 407 and 429 guide.

Finding out which hop refused you

This script reads the CONNECT result and both challenge headers from one request. It ran under macOS’s bash 3.2.57 against the bench above and gave the same answers under zsh 5.9. Pass the curl options as separate words. We once kept them in one variable and expanded it unquoted from zsh, which does not word-split the way bash does, and curl stopped with curl: option -k -x http://127.0.0.1:28407: is unknown. The first test in the script catches that, and any request that got no HTTP response at all, and prints curl’s exit code instead of blaming a hop.

#!/bin/bash
# whosaid.sh URL [extra curl args]  -> prints which hop refused the request
url=$1; shift
hdr=$(mktemp)
out=$(curl -sS -o /dev/null -D "$hdr" -w '%{http_code} %{http_connect}' "$@" "$url" 2>/dev/null)
rc=$?
read -r code connect <<<"$out"
if [ -z "$connect" ] || { [ "$code" = "000" ] && [ "$connect" = "000" ]; }; then
  echo "no HTTP response at all (curl exit $rc)"
elif [ "$connect" != "000" ] && [ "$connect" != "200" ]; then
  echo "proxy refused the CONNECT with $connect (origin never saw the request)"
elif grep -qi '^proxy-authenticate:' "$hdr"; then
  echo "proxy wants credentials: $code, $(grep -i '^proxy-authenticate:' "$hdr" | tr -d '\r')"
elif grep -qi '^www-authenticate:' "$hdr"; then
  echo "origin wants credentials: $code, $(grep -i '^www-authenticate:' "$hdr" | tr -d '\r')"
else
  echo "status $code, $(grep -i '^server:' "$hdr" | tail -1 | tr -d '\r')"
fi
rm -f "$hdr"
$ ./whosaid.sh https://127.0.0.1:28443/open/ok.txt -k -x http://127.0.0.1:28407
proxy refused the CONNECT with 407 (origin never saw the request)
$ ./whosaid.sh https://127.0.0.1:28443/basic/ok.txt -k -x http://puser:proxy-pass@127.0.0.1:28407
origin wants credentials: 401, WWW-Authenticate: Basic realm="origin-area"
$ ./whosaid.sh http://127.0.0.1:28401/open/ok.txt -x http://127.0.0.1:28407
proxy wants credentials: 407, Proxy-Authenticate: Basic realm="test-proxy"
$ ./whosaid.sh http://127.0.0.1:28401/forbidden-by-proxy/x -x http://puser:proxy-pass@127.0.0.1:28407
status 403, Server: squid/6.13
$ ./whosaid.sh http://127.0.0.1:28401/forbidden/ok.txt -x http://puser:proxy-pass@127.0.0.1:28407
status 403, Server: Apache/2.4.67 (Unix) LibreSSL/3.3.6
$ ./whosaid.sh https://127.0.0.1:443/ -k -x http://puser:proxy-pass@127.0.0.1:28407
proxy refused the CONNECT with 403 (origin never saw the request)

The same logic in Python, run with requests 2.32.3 on Python 3.9.6. On an HTTPS URL the proxy’s code exists only inside the exception message, so that is where the function looks. It matches the whole phrase Tunnel connection failed: NNN rather than any “407” in the text, because the same message also carries the target port and URL path. The -W ignore in the runs below only hides urllib3 2.3.0’s NotOpenSSLWarning, which it prints because macOS’s system Python is built against LibreSSL 2.8.3.

import os, re, requests

PROXY = os.environ.get("PROXY", "http://user:pass@gw.example.net:8000")

def classify(url):
    try:
        r = requests.get(url, proxies={"http": PROXY, "https": PROXY}, timeout=15)
    except requests.exceptions.ProxyError as e:
        # HTTPS target: the proxy refused the CONNECT, so there is no status code
        m = re.search(r"Tunnel connection failed: (\d{3})", str(e))
        code = m.group(1) if m else None
        if code == "407":
            return "proxy wants credentials (407 on CONNECT)"
        if code == "403":
            return "proxy policy refused the tunnel (403 on CONNECT)"
        if code:
            return "proxy answered the CONNECT with " + code
        raise
    if r.status_code == 407:
        return "proxy wants credentials: " + r.headers.get("Proxy-Authenticate", "")
    if r.status_code == 401:
        return "origin wants credentials: " + r.headers.get("WWW-Authenticate", "(no challenge sent)")
    if r.status_code == 403:
        return "403 from " + r.headers.get("Server", "unknown server")
    return str(r.status_code)

if __name__ == "__main__":
    import sys
    for u in sys.argv[1:]:
        print(u, "->", classify(u))
$ PROXY=http://127.0.0.1:28407 /usr/bin/python3 -W ignore classify.py \
    https://127.0.0.1:28443/open/ok.txt http://127.0.0.1:28401/open/ok.txt
https://127.0.0.1:28443/open/ok.txt -> proxy wants credentials (407 on CONNECT)
http://127.0.0.1:28401/open/ok.txt -> proxy wants credentials: Basic realm="test-proxy"

$ PROXY=http://puser:proxy-pass@127.0.0.1:28407 /usr/bin/python3 -W ignore classify.py \
    http://127.0.0.1:28401/basic/ok.txt http://127.0.0.1:28401/forbidden/ok.txt \
    http://127.0.0.1:28401/forbidden-by-proxy/x https://127.0.0.1:443/
http://127.0.0.1:28401/basic/ok.txt -> origin wants credentials: Basic realm="origin-area"
http://127.0.0.1:28401/forbidden/ok.txt -> 403 from Apache/2.4.67 (Unix) LibreSSL/3.3.6
http://127.0.0.1:28401/forbidden-by-proxy/x -> 403 from squid/6.13
https://127.0.0.1:443/ -> proxy policy refused the tunnel (403 on CONNECT)

And in Node 24.2.0 with the built-in fetch, where the proxy’s code has to be pulled out of the nested cause. The runs below set NODE_TLS_REJECT_UNAUTHORIZED=0 only because the test origin used a self-signed certificate; leave it out against real sites. Without it, the 401 URL failed with self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca. That is a TLS error at the origin, not a proxy refusal, which is why the script names a code only when the message says Proxy response.

// NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://user:pass@gw.example.net:8000 node classify.mjs URL...
for (const url of process.argv.slice(2)) {
  try {
    const r = await fetch(url);
    if (r.status === 401) console.log(url, '-> origin wants credentials:', r.headers.get('www-authenticate'));
    else if (r.status === 403) console.log(url, '-> 403 from', r.headers.get('server'));
    else console.log(url, '->', r.status);
  } catch (e) {
    // the proxy's status is two causes deep: "Proxy response (407) !== 200 when HTTP Tunneling"
    const inner = e.cause?.cause?.message ?? e.cause?.message ?? e.message;
    const code = /Proxy response \((\d{3})\)/.exec(inner)?.[1];
    if (code) console.log(url, '-> proxy refused the tunnel:', code);
    else console.log(url, '-> failed before any HTTP status:', inner);
  }
}
$ NODE_TLS_REJECT_UNAUTHORIZED=0 NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://127.0.0.1:28407 node classify.mjs \
    https://127.0.0.1:28443/open/ok.txt
https://127.0.0.1:28443/open/ok.txt -> proxy refused the tunnel: 407

$ NODE_TLS_REJECT_UNAUTHORIZED=0 NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://puser:proxy-pass@127.0.0.1:28407 node classify.mjs \
    https://127.0.0.1:28443/basic/ok.txt https://127.0.0.1:28443/forbidden/ok.txt https://127.0.0.1:443/
https://127.0.0.1:28443/basic/ok.txt -> origin wants credentials: Basic realm="origin-area"
https://127.0.0.1:28443/forbidden/ok.txt -> 403 from Apache/2.4.67 (Unix) LibreSSL/3.3.6
https://127.0.0.1:443/ -> proxy refused the tunnel: 403

The bench used Basic authentication on both hops because both programs ship it. Digest, Bearer and NTLM change the challenge string, not the rules above: the status code still says which kind of refusal it is, and the header name still says which hop asked.

Frequently asked questions

What is the difference between 401 and 403?
A 401 says the request lacks valid credentials and must include a WWW-Authenticate header explaining how to authenticate. A 403 says the server understood the request and refuses it, and RFC 9110 tells clients not to repeat it with the same credentials. In short, 401 means log in, 403 means you are not allowed.
Is 407 the same as 401?
It is the proxy's version. RFC 9110 defines 407 as similar to 401 but for authenticating to a proxy, with a Proxy-Authenticate challenge instead of WWW-Authenticate. You answer it with Proxy-Authorization, which the first proxy that asked for it consumes. On our bench Squid did not pass it on to the site.
Should an expired token return 401 or 403?
401. RFC 6750 maps an expired, revoked or malformed bearer token to the invalid_token error with status 401. A valid token that lacks the required scope is insufficient_scope with status 403.
Why does curl show http_code 000 when the proxy returns 407?
For an HTTPS URL the 407 answers curl's CONNECT request, so no response from the site ever arrives. curl puts the proxy's code in the http_connect write-out variable and exits with code 56 and the message "CONNECT tunnel failed, response 407".
Can a proxy return 403?
Yes. Any proxy with an access policy can. Squid 6.13 on our test bench returned 403 with X-Squid-Error: ERR_ACCESS_DENIED for a path its rules denied. Check the Server header, and whether the 403 arrived on the CONNECT, before blaming the target site.
Why do I get 401 with the right password?
Apache by default answers an authenticated user who is not authorized with 401 rather than 403, so the status does not confirm the password. Its error log tells the two apart: AH01617 for a password mismatch, AH01631 for an authorization failure.

Sources

  1. RFC 9110 §15.5.2: 401 Unauthorized
  2. RFC 9110 §15.5.4: 403 Forbidden
  3. RFC 9110 §15.5.8: 407 Proxy Authentication Required
  4. RFC 9110 §11.6.1: WWW-Authenticate
  5. RFC 9110 §11.7: Proxy-Authenticate and Proxy-Authorization
  6. RFC 6750 §3.1: Bearer token error codes
  7. Apache httpd 2.4: AuthzSendForbiddenOnFailure
  8. Squid wiki: Squid log files, result and hierarchy codes
  9. curl man page: --write-out http_code and http_connect
  10. libcurl error codes: CURLE_RECV_ERROR (56)
  11. Node.js CLI: NODE_USE_ENV_PROXY
  12. Django REST Framework: unauthorized and forbidden responses
  13. GitHub REST API: 404 Not Found for an existing resource
  14. Amazon S3 GetObject: 403 versus 404 and s3:ListBucket
  15. Distribution registry: token authentication specification

Read this page as Markdown · Quote it freely under CC BY 4.0 with a link back.