This works fine except when I use slashes in the query for search engines. For example, https://go.domain.example/g/foo/bar will search for foo only on Google, instead of foo/bar
How can I fix this?
I know I can extract the substring I want with regexes, but I’m afraid I can’t do that and use map at the same time.
I wonder if you could just route your engine matcher to a uri strip_prefix {path.0} and then redir to {engine}{uri} instead? Probably a lot faster than a regex.
Quick test seems to indicate it should work exactly as expected:
Yep - that’s because directives are evaluated in a specific order regardless of where they’re placed in the Caddyfile, by default: Caddyfile Directives — Caddy Documentation
The redir directive is normally processed before uri directives are. Using a route allows you to override the directive order, enabling URI manipulations to take place prior to the redirect.
Just two suggestions:
This can be a fast substring uri strip_prefix {path.0}/ instead of a more expensive regex manipulation.
This can also be handled slightly better. Ideally you don’t need to select for this matcher because the path will ALWAYS be some form of /*, but right now it looks like you’re using regex to get rid of the leading slash. You can just do this in another route with no matcher at all, again optimising away a regex operation:
route {
uri strip_prefix /
redir https://www.google.com/search?q={uri} 301
}
That’s pretty much all, though. The rest looks like a pretty well-formed Caddyfile to produce the specific set of results you’re after. I think it looks quite good.