Behavior of file_server in Caddyfile

I read the docs and when using a json file for configuration, file_server by default is run with pass-through disabled. If a file is not found, it will not pass onto the next directive but will throw an error.

I am using a Caddyfile and it I am considering two approaches to confguration:

  @notStatic {
    not file {
      root /some/dir
    }
  }
  reverse_proxy @notStatic localhost:3000

  file_server {
    root /some/dir
  }

or

  file_server {
    root /some/dir
  }
  reverse_proxy @notStatic localhost:3000

It seems that both configurations have the same result? Does this mean that file_server is run by default in pass-through mode with Caddyfile?

Would there be an advantage to one or the other? I like the second approach better since it is shorter but maybe it might have some unintended consequences? (be slower / less secure)

If I could also please ask - are there any downsides to using reverse_proxy with a tcp address vs using socket?

Thank you very much for any help you can give me on this! :pray:

I’m not sure if I’m understanding what point you’re confused on, but I think it has to do with not realizing that directives in the Caddyfile are sorted according to a pre-determined order:

file_server will always be sorted after reverse_proxy, unless you use route to override the order. Regardless of the order though, if either of those is handling the request, they won’t fall through to the other… unless you’re using a request matcher to specify when either should apply.

Since you’re using root for multiple different purposes (the file server and for the file matcher), it’s much better to use the root directive rather than specifying the root subdirective for each of those.

So, I think what you want is effectively this:

example.com {
	root * /some/dir

	@notStatic not file
	reverse_proxy @notStatic localhost:3000

	file_server
}

It would be more efficient to use a matcher that doesn’t need to read from disk though, like using a path matcher, if possible. It depends how your files are structured though. Are all your static assets in a /static directory? Then you could do @notStatic not path /static* instead.

I highly recommend you read through the Caddyfile Concepts page top to bottom, it should explain most of what you need to know:

Also, I will note that there’s no inherent runtime difference between JSON and Caddyfile. The Caddyfile is implemented as an adapter that outputs a JSON config that gets fed to Caddy. You can use the caddy adapt command to see what JSON your Caddyfile adapts to.

1 Like

Thank you so much @francislavoie, this has been super helpful!

1 Like