Basicauth + handle_errors issue persists

1. Caddy version (caddy version):

v2.4.6

2. How I run Caddy:

systemd

a. System environment:

Arch, systemd

b. Command:

N/A

c. Service/unit/compose file:

N/A

d. My complete Caddyfile or JSON config:

{
    admin off
    email name@mysite.com
    key_type rsa4096
}

(standards) {
    encode zstd gzip
    file_server
    header {
        Referrer-Policy "same-origin"
        Cache-Control "max-age=31536000"
        X-XSS-Protection "1; mode=block"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "deny"
    }
    tls {
        protocols tls1.2 tls1.3
    }
}

mysite.com, www.mysite.com {
    root * /var/www/mysite
    import standards
    basicauth /secret/* {
	foo (hashed-password-here)
    }
    handle_errors {
	redir https://mysite.com
    }
}

3. The problem I’m having:

Others have posted about the “handle_errors” directive conflicting with the “basicauth” directive since 2019, and to the credit of the Caddy team, a fix was implemented, but I’m still experiencing the issue on a brand new Arch server with the latest Caddy release, adhering to the official Caddy documentation.

4. Error messages and/or full log output:

curl -I https://mysite.com/secret responds:

HTTP/2 302 
location: https://mysite.com
server: Caddy
www-authenticate: Basic realm="restricted"

In a browser, mysite.com/secret redirects to mysite.com

5. What I already tried:

If I remove the handle_errors directive, it responds:

HTTP/2 401 
server: Caddy
www-authenticate: Basic realm="restricted"

In a browser, mysite.com/secret now works.

6. Links to relevant resources:

You’ll need to use matchers in your handle_errors to write the 401 status code again if that’s the error that was emitted.

So I guess the solution is this?

mysite.com, www.mysite.com {
    root * /var/www/mysite
    import standards
    basicauth /secret/* {
        foo (hashed-password-here)
    }
    handle_errors {
        @nope expression `{http.error.status_code} == 404`
            handle @nope {
	            respond {http.error.status_code}
	            redir https://mysite.com
            }
    }
}

If this is such a common, known issue, shouldn’t the basicauth directive documentation page make it clear that it conflicts with the handle_errors directive, and that this is the recommended implementation?

You’re right, we should improve the docs on this. If you want to take a crack at it, the docs are here: GitHub - caddyserver/website: The Caddy website

Your solution looks okay, I guess it’ll just fall through and write the original error if you didn’t specifically handle it. And if you only care about redirecting 404s, then that should be fine.