如何在HAProxy中设置动态变量? [英] How do I set a dynamic variable in HAProxy?
问题描述
是否可以设置一个动态变量,该变量将保存HTTP标头的内容,例如Host/X-Forwarded-Host,是否会在以后的ACL中使用?
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
推荐答案
在这里您可以混合使用多种技术.您完全不需要变量即可根据主机地址设置ACL,并使用这些ACL选择后端.就像这样简单:
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?
更新:以下是根据Host标头选择后端的方法:
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
# ..
这将设置一个变量,该变量在请求的上下文中有效,使用Host标头的值小写并用下划线替换句点.实际上,您甚至不需要变量:
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)]
如果找不到与Host标头匹配的后端,
HAproxy将返回503.如果您希望将这样的请求发送到其他地方,则可以设置default_backend
(我对此进行了测试,并且至少在1.6.3中有效).
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).
这篇关于如何在HAProxy中设置动态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!