Blog

Caddy. Reverse Proxy a Subdirectory Path

Caddy is a great web server, that I currently prefer over Apache and Nginx. This is due to the ease of setup (single executable), automatic handling of SSL certificates, and of course super simple initialization file (Caddyfile)

Caddy also is a great reverse proxy and works great on full domain names. Setting it up is a single line, and simply a pleasure working with it.

However, if you want to reverse proxy on a subfolder path, it may not be so obvious. The only Google searches that came back were only leading me in a wrong direction. So hopefully this can save you a morning or afternoon of your life.

In my case, I wanted to store the media files of a website on DigitalOcean spaces, but served them under the media/* path. Below is the Caddyfile how to do it.

Language: css
website.com {
    log {
      output file /home/www/website.com/storage/logs/caddy.log
    }

    # Resolve the root directory for the app
    root * /home/www/website.com/public

    # Provide Zstd and Gzip compression
    encode zstd gzip

    # Enable PHP-FPM
    php_fastcgi unix//run/php/php8.1-fpm.sock

    # Allow caddy to serve static files
    file_server

    # Proxy pass media to DigitalOcean
    handle_path /media/* {
        reverse_proxy https://website.ams3.digitaloceanspaces.com {
           header_up Host website.ams3.digitaloceanspaces.com
        }
    }
}

Quick explanation of the Caddyfile above, as it is a bit bigger that most of the caddy files. As you have probably already guessed this is a Laravel website, served by Caddy. The public folder of Laravel is served as a static file server. And all the requests starting with /media/ are proxy passed to DigitalOcean, which holds the media files.