Path_regexp vs. other matchers

1. Caddy version (caddy version):

# ./caddy version
v2.4.6 h1:HGkGICFGvyrodcqOOclHKfvJC0qTU7vny/7FhYp9hNw=

2. How I run Caddy:

a. System environment:

Linux

b. Command:

./caddy run

d. My complete Caddyfile or JSON config:

:444 {
	@old path_regexp old ^/old/(.*\.pdf)$
	redir @old /new/{re.old.1}
	redir /old/* /new/test
}

3. The problem I’m having:

The redirect with the regexp matcher only works when the second redir is removed.

# http :444/old/test.pdf
HTTP/1.1 302 Found
Content-Length: 0
Date: Mon, 21 Feb 2022 19:08:42 GMT
Location: /new/test
Server: Caddy

4. Error messages and/or full log output:

There is no output in the log regarding the problem. The second redir simply seems to have precedence.

5. What I already tried:

I can’t find anything in the documentation about matcher precedence. Or any other helpful information.

6. Links to relevant resources:

The Caddyfile adapter will sort directives with the same name according to the matchers where possible, by the length of the path matcher (more characters in the matcher means it gets sorted first).

This means that any path matcher will “win” and any other kind of matcher will be sorted afterwards. There’s no valid way to sort regexps except by hand, because it’s not possible to guess how a regexp will work from outside.

You can see the order they were sorted in by running caddy adapt --config /path/to/Caddyfile --pretty which will show you the JSON for your config. Notice that the /old/* path matcher gets sorted before the path_regexp matcher in the routes.

So to work around this, you’ll need to use a route to wrap these and force the order they get executed in.

:444 {
	route {
		@old path_regexp old ^/old/(.*\.pdf)$
		redir @old /new/{re.old.1}
		redir /old/* /new/test
	}
}

Thank you very much for the reply.
I suggest adding the description to the matcher documentation page. At least this was the place I was looking for information.

Good point. I opened an issue to remind us to do that at some point:

1 Like

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