问题
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
# ...
set-var s1(Host)
acl site1 hdr_end(host) -i %[s1]
# ...
use_backend %[s1] if site1
回答1:
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).
来源:https://stackoverflow.com/questions/39333496/how-do-i-set-a-dynamic-variable-in-haproxy