Caddy 2 matchers - AND and OR

Just looking for clarification that the documentation doesn’t mention…

I understand that different matchers in a matcher block are ANDed; also that a list of matches in a path or path_regexp line are ORed.

But what happens if you have multiple path or path_regexp lines? Are these recognised as logical continuations, and so ORed? After all, if they were ANDed they would always fail! Is this an allowed way of writing? Would they need to be adjacent?

Paul

I wasn’t certain how path_regexp would behave in particular, so I gave it a shot.

Adapting this Caddyfile:

:80
@match {
	path_regexp Foo ^/foo$
	path_regexp Bar ^/bar$
}
respond @match "Foo" 200

Gives this JSON:

{
  "apps": {
    "http": {
        "srv0": {
          "listen": [
            ":80"
          ],
          "routes": [
            {
              "match": [
                {
                  "path_regexp": {
                    "name": "Bar",
                    "pattern": "^/bar$"
                  }
                }
              ],
              "handle": [
                {
                  "body": "Foo",
                  "handler": "static_response",
                  "status_code": 200
                }
              ]
            }
          ]
        }
      }
    }
  }
}

You’ll notice that the first path_regexp actually gets dropped altogether, because the path_regexp matcher doesn’t support having two of them in one matcher set. This is a limitation of the Caddyfile at this time.

It is possible to get OR behaviour though, albeit super wacky:

@either {
	not {
		not path_regexp Foo ^/foo$
		not path_regexp Bar ^/bar$
	}
}
respond @either "Either"

This essentially does the boolean logic not (not Foo && not Bar) which is the same as Foo || Bar.

This is an area we’re looking to improve, for example this suggested feature (which is looking difficult to implement):

That said, path matchers do correctly get ORed, since a path matcher is defined as an array of paths.

The best way to verify for now is to look at the caddy adapt command’s output.

2 Likes

Thanks - that makes the present status clear. I have multiple path_regexp’s, so I’m just treating them separately for now:

    @forbidden1 path_regexp /(\.git|cache|bin|logs|backups|tests)/.*$
    rewrite @forbidden1 /forbidden
    @forbidden2 path_regexp /(system|vendor)/.*\.(txt|xml|md|html|yaml|php|pl|py|cgi|twig|sh|bat)$
    rewrite @forbidden2 /forbidden
    @forbidden3 path_regexp /user/.*\.(txt|md|yaml|yml|php|pl|py|cgi|twig|sh|bat)$
    rewrite @forbidden3 /forbidden
    @forbidden4 path_regexp /(LICENSE\.txt|composer\.lock|composer\.json|nginx\.conf|web\.config|htaccess\.txt|\.htaccess)
    rewrite @forbidden4 /forbidden

    respond /forbidden 403

(this is from the Grav CMS setup)

Paul

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