How can I secure an api endpoint from direct IP access

I don’t think accessing port 8000 directly involves Caddy at all since you haven’t configured Caddy to listen on port 8000. Instead, you’re connecting directly to your backend. Since the connection doesn’t involve Caddy, Caddy cannot help you there.

You should probably configure your backend to only listen on localhost by binding it to localhost:8000 or 127.0.0.1:8000 instead of listening to port 8000 on all available addresses. That way, only programs on your own machine can access it (Caddy being one of them). If your API does not have a way to configure this and you can’t change its code, configure your firewall to not allow connections to port 8000 from the outside.

If you want only Caddy to be able to access it, you could configure that using Docker: set up a bridge network, attach containers for Caddy and the API to it, update the Caddyfile to point to the service name for the API container instead of localhost, and only expose Caddy’s ports (typically 80 and 443) to the outside world.

1 Like