Search code examples
cloudflarecloudflare-workers

How to properly implement multiple domain routing based on a custom field in request header with Cloudflare?


could someone please suggest the proper way to implement multiple domain routing based on a custom field in request header?

My use case is, I have a service located in 2 different regions, resulting in two separate AWS ELBs: KR ELB and SG ELB. When FE sends requests to the service, the request header includes a field named region, which we’ll use to determine which ELB the request should connect to. We have identified two ways to implement regional routing:

  1. Origin Rules
  2. CF workers

for #1, it appears to perfectly meet our requirements by allowing us to define a rule and override the domain. no code work, GUI configuration, no additional cost. it’s great. unfortunately, seems it doesn’t support a custom field in request header yet. we have to use a existing field instead of a custom field. (as a workaround, we can put the field in query string which is supported by Origin Rules, but it’s not ideal from a design perspective)

for #2, CF worker is highly flexible, we’ve used it to implement various functionalities like caching, redirecting, etc. it’s easy to implement a worker for routing requests based on a field in request header. but we do have some concerns. such as: the new worker needs to match all traffic (with a route like route = abc.com/*) which could potentially increase latency, cost, affected scope we need to implement the code ourselves and carefully consider the proper way to chain multiple workers, as this process could lead to potential bugs

Could anyone kindly share any ideas about this? I would greatly appreciate it


Solution

  • I recommend you use #1 Origin Rules because you can use http.request.headers field in the expression like

    any(http.request.headers["yourcustomheadername"][*] == "sg")
    

    This is my blog post containing the example origin routing based on WebSocket header.

    Cloudflare Origin Rules を使って WebSocket 通信を別オリジンにルーティングする - Qiita