Caddy Basic Authentication
Caddy basic authentication examples
Caddyfile with Basic Auth protecting the site
Below is a minimal, complete Caddyfile based on your example (port 8999) that adds HTTP Basic authentication using bcrypt hashes. Replace usernames and hashes as needed.
:8999 {
root * /var/www/test-site
basicauth /* {
alice $2y$12$EXAMPLEHASHFORALICE............
bob $2y$12$EXAMPLEHASHFORBOB.............. # (2)!
}
file_server
}Always encrypt passwords!
Always encrypt passwords!
How to generate bcrypt hashes (recommended)
Run on the server (replace mypassword with the real one):
caddy hash-password ----plaintext mypasswordPaste each generated hash in place of the example hashes (behind the user name).
Notes
You can scope auth to a subpath (e.g., basicauth /admin/* { … }) instead of protecting the whole site.
For testing only, you may use plaintext credentials:
Like this:
basicauth /* {
alice s3cr3t
}!!! warning “Do not use plaintext in production.*”
How to allow a specific folder(s) to be public, but the rest of the site need to be password protected
Use basicauth on the site root, then exempt the public folder(s) by placing an explicit route for them before the protected block. Example (protect everything except /public and /static):
:8999 {
root * /var/www/test-site
# Public paths (no auth) — evaluated first
route /public* {
file_server
}
route /static* {
file_server
}
# All other requests require basic auth
basicauth /* {
alice $2y$12$EXAMPLEHASHFORALICE............
bob $2y$12$EXAMPLEHASHFORBOB..............
}
# Default file server for protected content (after auth)
file_server
}Notes
Generate bcrypt hashes with: caddy hash-password –bcrypt If the public folders should still be served from filesystem but within same file_server, keep the public route(s) first so they bypass basicauth. You can also use exact paths (e.g., /public/) or multiple route blocks for finer control.
Protect a proxied site with Basic Auth
Add a basicauth (or http.basic_auth) directive before reverse_proxy so requests are authenticated before being proxied. Example Caddyfile protecting the entire proxied site with bcrypt-hashed users:
https://our.public-site.com {
basicauth /* {
alice $2y$12$EXAMPLEHASHFORALICE............
bob $2y$12$EXAMPLEHASHFORBOB..............
}
reverse_proxy http://192.168.xxx.xxx:8080
}To allow one public subpath (e.g., /health) while protecting the rest, place a route that serves or proxies that path first:
https://our.public-site.com {
# Public endpoint (no auth)
route /health* {
reverse_proxy http://192.168.xxx.xxx:8080
}
# Everything else protected
basicauth /* {
alice $2y$12$EXAMPLEHASHFORALICE............
}
reverse_proxy http://192.168.xxx.xxx:8080
}!!! note “Generate bcrypt hashes for the passwords!”
Reload Caddy after editing:
caddy reload
# or:
sudo systemctl reload caddy.
# depending on your installationThat’s All folks!