How do I set a dynamic variable in HAProxy?

前端 未结 1 1340
长发绾君心
长发绾君心 2021-01-21 08:37

Is it possible to set a dynamic variable which will hold the content of HTTP header e.g. Host/X-Forwarded-Host and would be used later in ACLs?

frontend web1
  #         


        
相关标签:
1条回答
  • 2021-01-21 08:58

    You have a mix of techniques here. You don't need variables at all to set ACLs based on the host address and select a backend using those ACLs. That would be something simple like:

    frontend web1
      # ...
      acl site1 hdr(host) -i example.com
      acl site2 hdr(host) -i example.net
      # ...
      use_backend com if site1
      use_backend net if site2
    

    Is that all you're trying to do, or are you trying to accomplish something more sophisticated?

    UPDATE: Here's how to select a backend based on the Host header:

    frontend web1
      # ..
      http-request set-var(req.s1) req.hdr(Host),field(1,:),lower,regsub(\.,_,g)
      use_backend %[var(req.s1)]
    
    backend example_com
      # ..
    
    backend example_net
      # ..
    

    This sets a variable that is valid in the context of the request, using the value of the Host header lowercased and with periods replaced with underscores. Actually, you don't even need a variable:

    frontend web1
      # ..
      use_backend %[req.hdr(Host),field(1,:),lower,regsub(\.,_,g)]
    

    HAproxy will return 503 if a backend that matches the Host header cannot be found. You can set a default_backend if you want such requests to go somewhere else (I tested this and it works in 1.6.3, at least).

    0 讨论(0)
提交回复
热议问题