How to set proxy except root directory

I want to set up caddy to proxy all requests except those for static files in root directory. My Caddyfile looks like this:

mydomain {
    root /var/www/
    proxy / myproxy {
        websocket
        except /subdir /index.html
    } 
}

With that, “https://mydomain/subdir/” is fine, but “https://mydommain/” gets “Bad Request”. I suppose the request has been proxied, and that is not my intention. How can I assure caddy responses with “https://mydomain/index.hmtl” rather than turning it to the proxy? Thanks!

You’ve got two main ways to go about this.

First option - you can introduce a rewrite, with the proxy as the fallback option, that prioritizes serving static files. This is a broad, “serve a static file if it exists, otherwise, proxy the request”.

example.com {
  root /var/www
  rewrite {
    to {path} {path}/ /proxy-target{uri}
  }
  proxy /proxy-target/ myproxy {
    websocket
    without /proxy-target
  }
}

Second option - instead of prioritizing existing files, you can specifically rewrite any request that isn’t /index.html or /subdir to the proxy target.

Note that the canonical way to request /index.html is simply to request /, and Caddy’s server will redirect clients in this manner, so you can expect a client will always request / if they want /index.html.

example.com {
  root /var/www
  rewrite {
    if {path} not /
    if {path} not_starts_with /subdir
    to /proxy-target{uri}
  }
  proxy /proxy-target/ myproxy {
    websocket
    without /proxy-target
  }
}

Intuitive and helpful. Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.