You can password-protect a website in Caddy using the basicauth directive. Here’s how to do it:
1. Add Basic Authentication to Your Caddyfile
Edit your Caddyfile (/etc/caddy/Caddyfile) and add basicauth to the site you want to protect.
my.website.local {
root * /var/www/html/My/Website
file_server
basicauth / {
username hashed_password
}
}
- Replace
usernamewith your desired login name. - Replace
hashed_passwordwith a bcrypt-hashed password (see below how to generate one). - The
/means that the entire site is protected.
2. Generate a Bcrypt-Hashed Password
Caddy requires passwords to be stored securely using bcrypt. You can generate one using:
caddy hash-password --plaintext "yourpassword"
Example output:
$2a$14$NLOHAcTtu7zBQ3Yy/aBiuOgh1EMHwny8VbKdf.AAqRXEXj6WGbWJm
Copy this hashed password and place it in your Caddyfile.
Example:
basicauth / {
admin $2a$14$NLOHAcTtu7zBQ3Yy/aBiuOgh1EMHwny8VbKdf.AAqRXEXj6WGbWJm
}
3. Reload Caddy
After updating the Caddyfile, reload Caddy to apply the changes:
sudo systemctl reload caddy
Now, when you try to access my.website.local, Caddy will prompt for a username and password.
Optional: Protect Only a Specific Directory
If you only want to protect a subdirectory (e.g., /admin), modify the basicauth rule like this:
basicauth /admin {
admin $2a$14$NLOHAcTtu7zBQ3Yy/aBiuOgh1EMHwny8VbKdf.AAqRXEXj6WGbWJm
}
This way, only thoughts.basil.local/admin will require authentication.
Multiple Users
You can add multiple users by specifying multiple lines:
basicauth / {
admin $2a$14$hashedpassword1
user2 $2a$14$hashedpassword2
}
This should work for basic password protection in Caddy.