caddycaddyfile

How to configure caddy to deliver static file for specific url?


I have created a api platform project with the API Platform distribution.

It comes with a caddy server with a configuration like this:

{
    http_port {$CADDY_PORT}
    # Debug
    {$DEBUG}
    # HTTP/3 support
    servers {
        protocol {
            experimental_http3
        }
    }
}

{$SERVER_NAME}

log

route {
    root * /srv/api/public
    mercure {
        # Transport to use (default to Bolt)
        transport_url {$MERCURE_TRANSPORT_URL:bolt:///data/mercure.db}
        # Publisher JWT key
        publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
        # Subscriber JWT key
        subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
        # Allow anonymous subscribers (double-check that it's what you want)
        anonymous
        # Enable the subscription API (double-check that it's what you want)
        subscriptions
        # Extra directives
        {$MERCURE_EXTRA_DIRECTIVES}
    }
    vulcain
    push

    # Add links to the API docs and to the Mercure Hub if not set explicitly (e.g. the PWA)
    header ?Link `</docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation", </.well-known/mercure>; rel="mercure"`
    # Disable Google FLOC tracking if not enabled explicitly: https://plausible.io/blog/google-floc
    header ?Permissions-Policy "interest-cohort=()"

    php_fastcgi unix//var/run/php/php-fpm.sock
    encode zstd gzip
    file_server
}

With this configuration all the incomming http requests are handle by my index.php (which is the default file for file_server directive) file at the root directory /srv/api/public.

I want to configure caddy to prevent the request to be handle by the index.php file when the request start with /file. This way in my /srv/api/public I can create a folder file and directly request the images I will put in with request like: http://localhost/file/my-image.png

How can I change my caddy file configuration to do that ?

Thank you.


Solution

  • You just need to use the handle_path directive:

    {$SERVER_NAME}
    
    log
    
    # add this directive
    handle_path /file/* {
        root * /srv/api/public/file
        file_server
    }
    
    route {
        root * /srv/api/public