Conditional proxying in Cowboy based on request headers

Hi All,

I’m using Cowboy 2.14.2 and would like to implement conditional request forwarding to an upstream server based on specific conditions (e.g., User-Agent header value).

Use case: When a request arrives with a specific User-Agent value (e.g., “XXXXXX”), I want Cowboy to act as a simple reverse proxy and forward the request to an upstream non-Erlang server, rather than handling it with my application logic.

Is there a built-in or recommended way to achieve this in Cowboy? Should I:

  1. Implement this logic in a middleware that intercepts requests before they reach my handlers?
  2. Use a custom handler that performs the HTTP proxying using an HTTP client like gun?
  3. Use a different approach altogether?

I would appreciate if someone could provide a code snippet or working example showing how to implement this.

Any guidance would be greatly appreciated.

Thanks,

. Erlang 28.1.1
. Ubuntu 24.04 LTS + macOS Tahoe 26.0.1
. rebar 3.25.1+build.5474.ref161b38cf on Erlang/OTP 28 Erts 16.1.1

Cowboy is an HTTP server and doesn’t provide any HTTP proxying functionality. You’ll need to integrate an HTTP client (such as httpc, hackney or gun) for that part.

In your question, it’s unclear whether you want some of the inbound requests proxied and the rest to make it to your cowboy handlers. If this is the case, and you’re filtering on something other than the path, then I’d use option 1: have the middleware recognise and divert the special traffic and allow everything else to be routed by the default dispatcher.

If you’re proxying everything, then option 2: a custom handler using an HTTP client.

However: if it were me, I wouldn’t do this in cowboy at all. I’d stick another reverse proxy in front of it, such as Caddy or nginx or Traefik.

That kinda depends on your scale, however.

2 Likes

@rlipscombe Thanks for the detailed response!

I’m going to explore doing this with a reverse proxy in front of Cowboy instead, as you suggested.
I’ll report back with how it goes.