How to redirect the rest of unmatch requests?

1. Caddy version (caddy version):

v2.1.1 h1:X9k1+ehZPYYrSqBvf/ocUgdLSRIuiNiMo7CvyGUQKeA=

2. How I run Caddy:

systemd, caddyfile

a. System environment:

systemd

b. Command:

paste command here

c. Service/unit/compose file:

paste full file contents here

d. My complete Caddyfile or JSON config:

:443 {
    import server

    @query-matcher query k=v
    reverse_proxy @query-matcher https://foo.local

    @api path /api/*
    reverse_proxy @api https://foo.local

    redir https://bar.local{uri}
}

3. The problem I’m having:

Hi, I am trying to proxy matched requests to foo.local, and redirect the rest of requests to bar.local.

But the config doesn’t work, it redirects ALL requests to bar.local.

4. Error messages and/or full log output:

5. What I already tried:

6. Links to relevant resources:

This is because the Caddyfile sorts directives based on a pre-defined order:

You’ll notice that redir is higher than reverse_proxy.

As noted in the docs, you can use the route directive to override the order, or you could use a not matcher to invert the matching logic. First with the route approach:

:443 {
	import server

	route {
		@query-matcher query k=v
		reverse_proxy @query-matcher https://foo.local

		reverse_proxy /api/* https://foo.local

		redir https://bar.local{uri}
	}
}

Note that the above will only work as-is with the upcoming v2.2.0 release (or latest on the master branch), because there was a bug preventing @ matchers from being defined inside of route blocks. If you prefer this approach, for now, you’ll need to move the @query-matcher line just before the route, but I wanted to show the “ideal” config here.

Alternatively with the negated matcher:

:443 {
	import server

	@query-matcher query k=v
	reverse_proxy @query-matcher https://foo.local

	reverse_proxy /api/* https://foo.local

	@redirect {
		not path /api/*
		not query k=v
	}
	redir @redirect https://bar.local{uri}
}

Note that I also inlined your /api/* path matcher because it saves a line :smile:

2 Likes

Thank you! :grinning:

1 Like

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