Restrict access to certain path
In Caddy, you can restrict access to certain paths based on the client's IP address using the remote_ip
matcher and the handle
directive. Here is an example Caddyfile configuration that allows only specific IP addresses to access the /admin
path:
example.com {
@admin {
path /admin*
remote_ip 192.0.2.1 192.0.2.2
}
handle @admin {
# Your directives for the admin area, e.g., reverse_proxy, file_server, etc.
# ...
}
handle {
# Directives for the rest of your site
# ...
}
}
In this configuration:
@admin
is a named matcher that matches requests for paths beginning with/admin
and originating from the IP addresses192.0.2.1
and192.0.2.2
.The
handle @admin
block will only apply to requests that match the@admin
conditions. You can place any directives you want inside this block to handle the requests for the admin area.The
handle
block without a matcher will catch all other requests that do not match the@admin
conditions.
If a client with an IP address that is not listed tries to access the /admin
path, they will receive a 404 Not Found response by default because there are no directives outside the handle
blocks that apply to the /admin
path.
For more advanced access control, you might want to look into using the basicauth
directive to require a username and password for the admin area or explore plugins that provide more sophisticated access control mechanisms.
When you have many path route to different backend serivce, you should write the caddy file as following
example.com {
@admin {
path /admin*
remote_ip 192.0.2.1 192.0.2.2
}
route /admin* {
handle @admin {
# Your directives for the admin area, e.g., reverse_proxy, file_server, etc.
# ...
}
handle {
# Directives for the rest of your site
# ...
}
}
route /path1* {
# Your directives to backend service A
# ...
}
route /path2* {
# Your directives to backend service B
# ...
}
}
The handle
directive is kind of similar to the location
directive from nginx config, The route
Evaluates a group of directives literally and as a single unit.
Refer:
评论区