When running a Caddy 2 webserver, you might want to prevent access to certain paths or sensitive files β for example, /admin, /config.php, or .env. Caddy makes this easy with its flexible matcher system.
Blocking specific paths
To block entire paths, define a named matcher and respond with a 403 Forbidden status:
example.com {
@blocked {
path /admin* /secret* /internal/*
}
handle @blocked {
respond "Access denied" 403
}
root * /var/www/html
file_server
}
In this example, requests to /admin, /secret, or /internal will all be denied before they reach your app or static files.
If you need to block paths globally (for all sites handled by Caddy), you can move this rule into the global options block:
{
@blocked {
path /wp-admin* /private*
}
handle @blocked {
respond "Access denied" 403
}
}
example.com {
root * /var/www/html
file_server
}
Blocking specific filenames
Caddy can also block requests for particular filenames, such as configuration or metadata files you donβt want exposed:
example.com {
@blocked {
path /config.php /composer.json /package-lock.json /.env
}
handle @blocked {
respond "Access denied" 403
}
root * /var/www/html
file_server
}
This setup denies direct access to those files, no matter where they are located in your document root.
If you want to catch filenames even when they appear in subdirectories, use a regular expression matcher instead:
@blocked path_regexp sensitive_files ^.*/(config\.php|\.env|composer\.json)$
handle @blocked {
respond "Access denied" 403
}
This will block /config.php, /foo/config.php, and /bar/.env.
Blocking by file extension
You can also block entire file types using a regex matcher:
@blocked path_regexp backup_files ^.*\.(bak|old|sql)$
handle @blocked {
respond "Access denied" 403
}
This prevents access to backup and SQL dump files, which are common sources of accidental data leaks.
Caddyβs matchers and the respond directive make it simple to protect sensitive paths and files. By adding a few lines to your Caddyfile, you can easily deny unwanted access before it ever reaches your application layer β keeping your server both faster and safer.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.