Caddy Web Server

repository·master·Indexed 42 days ago

https://github.com/caddyserver/website

A self-contained, static binary web server written in Go featuring an extensible plugin architecture. Documentation covers the administration REST API for zero-downtime configuration management, JSON configuration traversal using @id tags, PKI CA management, reverse proxy upstream monitoring, and the module lifecycle for version v2.7.6 and newer.

Tokens
92.1K
Snippets
399
Records
468
Agent score
51%

What's inside Caddy

  1. Introduction to Caddy

    master

    Caddy is an extensible platform written in Go designed to serve sites, services, and apps. It functions as a 'server of servers' that can take on the role of any long-running process via modules.

    Key characteristics:

    • Configuration: Supports dynamic and exportable configuration via an API. While no config files are strictly required, users typically use the Caddyfile format or native JSON configuration. Config adapters allow different formats to be converted into Caddy's native JSON.
    • Deployment: Compiles for all major platforms and has no runtime dependencies.
  2. Basic Caddy CLI usage

    master

    Caddy follows a standard unix-like command line interface. The general syntax for invoking commands is:

    caddy <command> [<args...>]

    Where:

    • <carets> indicate parameters to be replaced by your input.
    • [brackets] indicate optional parameters.
    • (brackets) indicate required parameters.
    • ... indicates a continuation (one or more parameters).
    • --flags may have single-letter shortcuts (e.g., -f).

    For a quick start, you can run caddy, caddy help, or man caddy (if the manpage is installed).

    caddy <command> [<args...]]
  3. Use the reverse_proxy directive

    master

    The reverse_proxy directive proxies requests to one or more backends. It supports configurable transport, load balancing, health checking, request manipulation, and buffering options.

    Basic Syntax:

    reverse_proxy [<matcher>] [<upstreams...>] {
        # configuration subdirectives
    }

    You can specify upstreams directly in the directive line or using the to subdirective.

    reverse_proxy localhost:8080 localhost:8081
  4. Use the route directive to control directive order

    master

    The route directive allows you to evaluate a group of directives literally and as a single unit. By default, Caddy reorders directives in the Caddyfile to optimize the HTTP handler chain. However, when you need absolute control over the execution order—specifically to ensure one handler runs before another regardless of Caddy's built-in sorting—you should wrap them in a route block.

    Key Rules:

    • Directives inside a route block are not reordered; they are executed in the exact order they are written.
    • Only HTTP handler directives (directives that add handlers or middleware to the chain) can be used inside a route block.
    • Subdirectives within a route block are treated as regular directives.
    route [<matcher>] {
    	<directives...>
    }
  5. How Caddy's architecture works

    master

    Caddy is composed of three primary components:

    1. Command: The CLI used to launch the process. While the core CLI is minimal, modules can add their own subcommands (e.g., caddy file-server) which may include their own flags and environment variables.
    2. Core Library: Manages configuration via Run() and Stop(). It handles top-level JSON fields like admin (for the admin API) and logging.
    3. Modules: The functional components of Caddy. Modules are plugins that extend Caddy's configuration structure.

    Key distinction: All modules are plugins, but not all plugins are modules. Modules specifically extend the Caddy JSON configuration structure.

  6. How response matchers work in Caddyfile

    master

    Response matchers allow you to filter or classify HTTP responses based on specific criteria. They are typically used within other directives to make decisions about a response as it is being written to the client.

    There are two ways to use them:

    1. Named Matchers: You declare a matcher with a name (prefixed with @) and then reference that name in a directive. This is useful for reusability.
    2. Inline Matchers: You provide the criteria directly within the directive without a prior declaration.
    # Named Matcher
    @name status 2xx
    
    directive @name {
        ...
    }
    
    # Inline Matcher
    ... status 2xx
  7. Use the rewrite directive to modify request URIs

    master

    The rewrite directive performs an internal rewrite of the request URI. It is primarily used for manipulating the path and query string. Because it is an internal rewrite, the client is unaware of the change, and the scheme or authority (host/port) remains unchanged.

    Key Behaviors

    • Intent: Implies the intent to accept the request but with modifications.
    • Mutual Exclusivity: Only the first matching rewrite directive in a block is executed. This prevents cascading rewrites within the same block.
    • Matcher Behavior: A request matcher used before a rewrite might not match the same request after the URI has been modified. To ensure a rewrite shares a route with other handlers, wrap them in route or handle directives.
    • URI Components: Only the components specified in the <to> argument (path or query) are operated on.
    rewrite [<matcher>] <to>
  8. Use the push directive for HTTP/2 server push

    master

    The push directive configures Caddy to pre-emptively send resources to the client using HTTP/2 server push. This is useful for reducing latency by sending critical assets (like CSS or JS) before the client explicitly requests them.

    Caddy can automatically push resources that are identified via Link headers in the response. It supports the following Link header formats:

    • <resource>; as=script
    • <resource>; as=script,<resource>; as=style
    • <resource>; nopush (Note: nopush prevents the resource from being pushed)
    • <resource>;<resource2>;...

    Constraints:

    • Only same-host resources (starting with /) can be pushed.
    • External resources or resources marked with nopush are ignored.
    • By default, Caddy automatically carries over safe headers (Accept-Encoding, Accept-Language, Accept, Cache-Control, and User-Agent) to the push requests.
    push
  9. Configure HTTP request logging with the log directive

    master

    The log directive enables and configures HTTP request logging (access logs) for the hostnames defined in the site block where it appears.

    Key behaviors:

    • Scope: It applies to the hostnames of the site block unless the hostnames subdirective is used to override them.
    • Default Behavior: When enabled, all requests to the site are logged by default.
    • Conditional Logging: To skip specific requests from being logged, use the log_skip directive.
    • Custom Fields: To add custom fields to log entries, use the log_append directive.
    • Security: By default, sensitive headers (Cookie, Set-Cookie, Authorization, and Proxy-Authorization) are logged as REDACTED. This can be changed via the log_credentials global server option.

    Note: To configure Caddy's internal runtime logs (as opposed to HTTP access logs), use the log global option instead of this directive.

  10. Caddyfile Matcher Syntax

    master

    In a Caddyfile, a matcher token can be placed immediately after a directive to limit its scope. Matcher tokens can take three primary forms:

    1. Wildcard (*): Matches all requests. This is the default behavior if no matcher is provided, so it is often omitted.
    2. Path (/path): Starts with a forward slash to match a request path. Note that path matching is an exact match by default; use a * suffix for prefix matching.
    3. Named Matcher (@name): Refers to a pre-defined set of matching criteria defined elsewhere in the site block.

    If a directive's syntax documentation shows [<matcher>], the matcher is optional.

    # Wildcard (matches everything)
    reverse_proxy localhost:9000
    
    # Path (matches /api/ prefix)
    reverse_proxy /api/* localhost:9000
    
    # Named (matches criteria defined in @postfoo)
    reverse_proxy @postfoo localhost:9000
  11. Define multiple sites in a single Caddyfile

    master

    To define multiple sites, you must wrap each site's configuration in curly braces { }. When using curly braces, the site address must appear before the opening brace, and all directives must reside inside the braces.

    You can also group multiple addresses that share the same configuration by separating them with commas.

    # Individual sites
    :8080 {
    	respond "I am 8080"
    }
    
    :8081 {
    	respond "I am 8081"
    }
    
    # Multiple addresses sharing one config
    :8080, :8081 {
    	...
    }