Default response if reverse_proxy doesn't match

I’m trying to send a default 404 response, if reverse_proxy doesn’t match: {
  basicauth /* {
    <user> <hash>

  reverse_proxy /folder* <ip>:80
  respond /* 404 {

but that’ll always return the 404 instead, is there a way to do this? the goal is to essentially only allow a single folder to be proxied, the rest to return 404.

Your issue is that with Caddyfile config, the directives are sorted according to a predefined order. respond is ordered before reverse_proxy, so it always takes precedence. See the directive order here in the docs:

You have two options to deal with this. Either you can use a route block to override the directive order, or you can use a not matcher to invert the matching.

First with a route:

route {
	reverse_proxy /folder* backend:80
	respond 404

And with a not matcher plus a path matcher:

@notFolder not path /folder*
respond @notFolder 404

reverse_proxy /folder* backend:80

I would say for your usecase, the route is probably the cleanest approach, but it depends what you need.

Also note, you can omit the /* matcher, because by default without it, it’s the same as having specified *, i.e. match all requests. And the close subdirective on respond is probably unnecessary for you here as well.


oh wow thanks! I never seen route before, out of the two I think route is much easier, also thanks for the respond note, I literally always used close inside assuming that’s necessary from the examples :slight_smile:

what about basicauth, should I also just use smth like basicauth { instead of basicauth /* { or does it not have such defaults like respond?

1 Like

All directives that support matchers work the same way (except handle_path which I think is the one exception in that it only supports path matchers and not named matchers), so yes you can omit the matcher for basicauth as well. If you see [<matcher>] in the syntax doc for a matcher, it allows for an optional matcher argument as described in the matcher docs:

1 Like

Awesome, thanks!

This topic was automatically closed after 30 days. New replies are no longer allowed.