Is there a way to better group this Caddyfile?

1. The problem I’m having:

Here is my Caddyfile snippet:

:80 {

	handle /api/* {
		reverse_proxy http://myserver:3030
	}
	handle_path /app1/* {
		reverse_proxy http://myserver:3030
	}
	handle_path /app2/* {
		reverse_proxy http://myserver:3030
	}
}

Since the proxy server is same, So I want to use named matcher to simplifie these Caddyfile, such as:

:80 {

	@myserver {
		path /api/*
		path /app1/*
		path /app2/*
	
	}
	handle @myserver {
		reverse_proxy http://myserver:3030
	}
}

But this is not right because app1 and app2 was use handle_path .

I searched the document but can’t find the right way to achive this.

2. Error messages and/or full log output:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

3. Caddy version:

caddy 2.7.4

4. How I installed and ran Caddy:

a. System environment:

ubuntu 22.04

b. Command:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

c. Service/unit/compose file:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

d. My complete Caddy config:

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

5. Links to relevant resources:

handle and handle_path are not the same. Are you intending to strip the matched path, or not?

That said, you can write your path matcher as a one liner like this:

@myserver path /api/* /app1/* /app2/*

The path /api/* and /app1/* have different processing logic. /api requires the use of handle, but /app1/* and /app2/* require the use of handle_path, so is there a simple way to handle this?

You could do this I guess:

:80 {
	uri /app1/* strip_prefix /app1
	uri /app2/* strip_prefix /app2
	reverse_proxy myserver:3030
}

All paths will go to your proxy, but your app paths will have their prefix stripped first.

If you have more than two apps then you could do:

:80 {
	@apps path_regexp apps ^(/app[0-9]+)(.*)$
	rewrite @apps {re.apps.2}
	reverse_proxy myserver:3030
}

This would match a path with any app number and rewrite it to the remainder of the path (i.e. (.*) the 2nd capture group)

2 Likes