Caddyfile v1 to v2

Hi Guys,

I need to maintain an service that use caddy v1.
I would love to update this to v2.
It has a simple Caddyfile → still i struggle with the rewrite rules on this.

V1:

localhost:8080
root /var/www/ev_content/offlinemode
rewrite {
if {path} not_match ^/api
if {path} not_match ^/img
to {path} {path}/ /
}

what i have done for V2 sofar:

localhost:8080
root * /var/www/ev_content/offlinemode

rewrite not path /api/* /
rewrite not path /img/* /

im struggeling with the rewrite rules / its not working …
what is wrong? im blind ?

Please read the “Syntax” section of the request matcher docs:

You’ll need to use a named matcher in this case, to use not.

I think what you want is this:

localhost:8080 {
	root * /var/www/ev_content/offlinemode

	@tryfiles {
		not path /api* /img*
		file {path} {path}/ /index.html
	}
	rewrite @tryfiles {http.matchers.file.relative}

	file_server
}

So what this is saying is “define a matcher called @tryfiles which matches when the path does not start with either /api or /img, AND when there is a file on disk that is either at {path} or {path}/ (for a directory) or /index.html (which should always exist)” – the file matcher here is a tautology, it will always match, but it does one important thing, and that’s populate the {http.matchers.file.relative} placeholder which is the path which it actually found on disk.

As an aside, you’ll notice there’s a try_files directive which does much the same thing, but we’re not using it here because it’s a shortcut for a matcher + a rewrite, it doesn’t support another matcher on it.

1 Like

wow - what a great answer!
Its working and i have all information i need to expand and learn!

TY!

1 Like

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