Redir doesn't add a regex group to URL

FROM caddy:2.0.0-builder

I recommend using Caddy v2.2.0 instead, there’s plenty of great fixes since v2.0 that you can make use of.

Please take a look at the docs on Docker Hub again, the instructions for building are very slightly different (use xcaddy now, and each plugin is prefixed with --with)

That said, the trouble with your rewrite is due to the order of operations. Unfortunately, you can’t rely on matchers to run in the order you define them in your Caddyfile. They’ll be run in an arbitrary order. That means you can’t rely on the result of the regexp in other matchers in the same named matcher block.

You can work around this limitation though, by using the handle directive to make sure the matchers are run in sequence (I’m using a feature introduced in v2.1 here, single line named matchers):

@staticPath path_regexp reg_static ^/static/(version\d*/)?(.*)$
handle @staticPath {
	@static file /static/{re.reg_static.2}
	rewrite @static /static/{re.reg_static.2}

	@dynamic not file /static/{re.reg_static.2}
	rewrite @static /static.php?resource={re.reg_dynamic.2}
}

So this way, we’re delegating use of the path_regexp matcher to inside of a new subroute, so we guarantee that the regexp has run before we use it. It also lets you remove a bit of duplication since you don’t need to repeat the regexp.

Turns out, you can actually shorten it even more here by using the try_files directive, which is a shortcut for a file matcher plus a rewrite:

@staticPath path_regexp reg_static ^/static/(version\d*/)?(.*)$
handle @staticPath {
	try_files /static/{re.reg_static.2} /static.php?resource={re.reg_dynamic.2}
}

I’m not 100% certain that this will work (I’m sketchy on whether the query is maintained in the rewrite here) but I hope it does! Note that the handle is still needed here, because the try_files directive is special and can’t take matcher arguments, since it itself encodes a matcher as part of the shortcut.

1 Like