After reverse proxying a request, I want to modify some text in the upstream response body before sending the result to the client. The logs show that the replace_response handler isn’t being invoked at all.
4. Error messages and/or full log output:
5. What I already tried:
I have tried different plugins. I have tried replacing something very simple like “html” to check that I am not making a typo in the config. I have checked the parsed config through curl -L "http://localhost:2019/config" | jq and can confirm that the handler is correctly registered.
The problem you’re seeing is due to directive ordering. The fix is to move replaceabovereverse_proxy in your snippet.
The way Caddy works is via a middleware-type system. Each handler is chained together by calling the next one in the chain, until one returns without calling the next in the chain, or the last handler is reached. This is how reverse_proxy works, because it’s a “terminal” handler, i.e. it’s a handler that acts as the end of the chain. The replace handler, like encode and a few others like header (if you use the defer option) run on the way back up the chain of handlers, i.e. after having called the next handler in the chain. So if you use route to set the order and have replaceafterreverse_proxy, then it never gets called because reverse_proxy doesn’t call it.
This is why the docs for replace recommend setting the order for replace like this:
{
order replace after encode
}
i.e. set its order to be after encode’s, which is another handler with the property of running on the way back up the chain. If you use the order global option, then you won’t need to wrap it in a route.