DEV Community

Edimar Cardoso for Quave

Posted on

Using Caddy to Serve Static Files Behind a Load Balancer

Caddy server has proven to be a very promising project. Not only is it fast, but it also has many built-in features that greatly simplify configuration. One example is the automatic issuance of SSL certificates. Moreover, it's very easy to set up a service using Caddy.

This week, I needed to create a service to publish static files. When trying to do this with Caddy's default configuration, I noticed it wouldn't be possible due to a slightly different scenario.

In my scenario, the service would run behind a load balancer at zCloud that's already responsible for generating certificates and handling TLS/SSL termination. The default configuration caused issues because it shouldn't generate an SSL certificate, but only serve files on the default HTTP port.

Additionally, there was another particularity: I needed a health check endpoint with public access, while everything else needed to be blocked using standard "Basic Auth" authentication.

Here's the file used to accomplish this in a simple way:

{
  auto_https off
}
:8080 {
    route /_health* {
        respond 200
    }
    route {
        basic_auth / {
            USER_NAME HASH_PASSWORD
        }
        root * /var/www/static
        file_server
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's break down the configuration:

Disabling SSL

auto_https off
Enter fullscreen mode Exit fullscreen mode

This disables automatic certificate issuance and disables redirection to HTTPS.

Port

:8080 {
# ...
Enter fullscreen mode Exit fullscreen mode

This specifies the port that will be opened to receive connections.

Health check

    route /_health* {
        respond 200
    }
Enter fullscreen mode Exit fullscreen mode

This route provides public access to the health check endpoint.

Static files with authentication

    route {
        basic_auth / {
            USER_NAME HASH_PASSWORD
        }
        root * /var/www/static
        file_server
    }
Enter fullscreen mode Exit fullscreen mode

This part of the configuration will receive all other requests, intercept them and force a login if the user is not logged in, and serve files from the /var/www/static directory.

The USER_NAME value is the username that will be used for authentication.
The HASH_PASSWORD value is the hash generated by the Caddy CLI based on the defined password. To generate this value, simply follow the instructions in the official basic_auth documentation.

Conclusion

This Caddy Server configuration offers an elegant solution for serving static files with authentication while allowing a public health check endpoint. Caddy's flexibility and simplicity make it an excellent choice for various deployment scenarios.

Top comments (0)