Caddy makes it easy to serve static files from different directories while still handling dynamic requests through a reverse proxy. If you need to serve multiple static paths separately from your main application, here's how you can configure it properly.

Let’s say you have the following static directories:

  • /media/ β†’ /shared/media
  • /images/ β†’ /subfolder/images
  • /assets/ β†’ /other/assets
  • Everything else should be proxied to a Phoenix application on port 4000.
www.mysite.com, mysite.com {
    encode zstd gzip
    header -Server

    # Serve /media from a specific folder
    handle_path /media/* {
        root * /shared/media
        file_server
    }

    # Serve /images from a specific folder
    handle_path /images/* {
        root * /subfolder/images
        file_server
    }

    # Serve /assets from a specific folder
    handle_path /assets/* {
        root * /other/assets
        file_server
    }

    # Proxy all other requests to Phoenix
    handle {
        root * /var/www/www.mysite.com
        reverse_proxy localhost:4000
    }
}
  • Each handle_path block ensures static files are served directly, preventing them from being forwarded to the proxy.
  • The final handle block catches everything else and proxies it to Phoenix.
  • This setup ensures proper separation of static and dynamic content while keeping the configuration clean and efficient.

By structuring your Caddyfile with handle_path, you can efficiently serve multiple static paths without interfering with your reverse proxy. This setup is particularly useful for web applications that need to serve assets, media files, or other static content alongside dynamic requests.