Haproxy 为子域添加响应 header

Haproxy add response header for subdomain

我尝试通过这种方式为子域添加 header:

acl ExampleRule hdr(host) -i subdomain.example.com
http-response set-header X-test "test" if ExampleRule

但是当我加载页面时,它没有被添加。有谁知道怎么添加吗?

有两个问题。

首先,http-responsehdr() 一起将导致测试响应 header,而不是请求 header。

hdr([<name>[,<occ>]]) : string

This is equivalent to req.hdr() when used on requests, and to res.hdr() when used on responses. Please refer to these respective fetches for more details. In case of doubt about the fetch direction, please use the explicit ones.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#7.3.6-hdr

所以,您想要使用 req.hdr()

但这还不够,因为无论声明顺序如何,ACL 条件评估都会延迟,并且仅当遇到引用 ACL 的语句时才动态完成。

在响应处理期间评估 ACL 时,req.hdr() 将不会匹配任何内容,因为为了提高效率,请求缓冲区会在请求发送到服务器后立即释放。它在响应处理期间不可用,因此没有请求提取可以return它的任何值——它已经被遗忘了。

因此,您需要在请求处理期间捕获事务变量中的header...

http-request set-var(txn.myhostheader) req.hdr(host)

...然后在响应处理期间评估变量的值。

acl ExampleRule var(txn.myhostheader) -i subdomain.example.com
http-response set-header X-test "test" if ExampleRule

或者最后两行可以替换为这一行(匿名 ACL):

http-response set-header X-test "test" if { var(txn.myhostheader) -i subdomain.example.com }

在每种情况下,变量名称是 txn.myhostheadertxn(必需)表示在请求和响应期间保持其值的变量 + .(必需) ) + myhostheader,这是我编的名字。