如何重定向到位于 HAProxy 后面的多个服务器,这些服务器具有不同的路径开头

How to redirect to multiple servers sitting behind HAProxy which have different path begining

我有 3 个服务器侦听以下端口,

> 10.21.5.39:80    -->   api.something.com
> 10.21.4.234:80    -->   *.something.com
> 10.21.5.73:80     -->   coolapi.something.com
> 10.21.5.73:3002    -->   school.something.com

我正在使用 HAProxy 服务器将流量重定向到这些后端,我在 haproxy 上使用以下配置,但似乎无法正常工作。

frontend api
       bind *:80
       acl url_api path_beg /api
       use_backend api-backend if url_api

frontend custui
       bind *:80
       acl url_custui path_beg *
       use_backend custui-backend if url_custui


frontend backoffice
       bind *:80
       acl url_backoffice path_beg /backoffice
       use_backend backoff-backend if url_backoffice

frontend partnerui
       bind *:80
       acl url_partnerui path_beg /partner
       use_backend partner-backend if url_partnerui


backend api-backend
    mode    http
    option  httpchk
    server  api01 10.21.5.39:80

backend custui-backend
    mode    http
    option  httpchk
    server  custui01 10.21.4.234:80

backend backoff-backend
    mode http
    option httpchk
    server backoff01 10.21.5.73:80


backend partner-backend
    mode http
    option httpchk
    server backoff01 10.21.5.73:3002

所以想法是让 HAProxy 监听 80,然后重定向到监听指定端口的后端。请帮助

几个问题:

  • 您有多个 frontends 都在侦听端口 80;我建议使用单一前端并使用 ACL 将流量定向到您的 backends。来自 the HAProxy documentation

    There may be as many "use_backend" rules as desired. All of these rules are evaluated in their declaration order, and the first one which matches will assign the backend.

  • 您提供 option httpchk,但不支持检查您的 server 行;来自 HAProxy 文档(具体为 1.5.18,但与其他版本相当)

    The port and interval are specified in the server configuration.

    我建议添加一个时间间隔(以毫秒为单位),例如

    server  custui01 10.21.4.234:80 check inter 2000
    
  • 您在每个后端指定了 mode httpoption httpchk;这些可以在 defaults 部分组合,然后在必要时在后端覆盖。

  • 我喜欢使用 hdr(host) 来检查 HTTP 请求的 URL,所以我会将 acl url_api path_beg /api 重写为 acl url_api hdr(host) -m beg api.,但这取决于个人喜好

将这些建议与您列出的要求相结合,这是您的配置文件的更新版本:

defaults
   mode    http
   option  httpchk

frontend something.com
   bind *:80

   acl url_api path_beg /api
   use_backend api-backend if url_api

   acl url_backoffice path_beg /backoffice
   use_backend backoff-backend if url_backoffice

   acl url_partnerui path_beg /partner
   use_backend partner-backend if url_partnerui

   # Catches anything not covered by use_backend above
   default_backend custui-backend

backend api-backend
    server  api01    10.21.5.39:80   check inter 2000

backend backoff-backend
    server backoff01 10.21.5.73:80   check inter 2000

backend partner-backend
    server backoff01 10.21.5.73:3002 check inter 2000

backend custui-backend
    server  custui01 10.21.4.234:80  check inter 2000