HAProxy:将X-Forwarded-For的中间IP转换为新的标头

时间:2016-05-09 09:43:37

标签: proxy ip haproxy x-forwarded-for

haproxy.cfg我尝试从x-forwarded-for标头中提取正确的IP地址为新的自定义标头。

我的输入请求标题类似于

X-Forwarded-For: 1.2.3.4, 2.3.4.5, 3.4.5.6

我期望的新标题会是:

X-Custom-IP: 2.3.4.5

感谢

1 个答案:

答案 0 :(得分:2)

原始答案:

您可以使用字段sample-fetcher transformation关键字: https://cbonte.github.io/haproxy-dconv/configuration-1.6.html#7.3.1-field

由于无法计算当前haproxy中的字段,我会在X-Forwarded-For标头上编写几个带有regexp的简单ACL,用于检测0,1,2,3,4,5种不同的IP(或实际上,逗号分隔符)并根据它,选择适当的字段放入X-Custom-IP。

E.g。 (未经测试)

acl x_forwarded_for_1_ips hdr(x-forwarded-for) -i (?:[0-9]{1,3}\.){3}[0-9]{1,3}
acl x_forwarded_for_2_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){1}(?:[0-9]{1,3}\.){3}[0-9]{1,3}
acl x_forwarded_for_3_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){2}(?:[0-9]{1,3}\.){3}[0-9]{1,3}
acl x_forwarded_for_4_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){3}(?:[0-9]{1,3}\.){3}[0-9]{1,3}
acl x_forwarded_for_5_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){4}(?:[0-9]{1,3}\.){3}[0-9]{1,3}

http-request add-header X-Custom-Ip %[hdr(x-forwarded-for)] if x_forwarded_for_1_ips
http-request add-header X-Custom-Ip %[hdr(x-forwarded-for),field(2,\,)] if x_forwarded_for_2_ips
http-request add-header X-Custom-Ip %[hdr(x-forwarded-for),field(2,\,)] if x_forwarded_for_3_ips
http-request add-header X-Custom-Ip %[hdr(x-forwarded-for),field(3,\,)] if x_forwarded_for_4_ips
http-request add-header X-Custom-Ip %[hdr(x-forwarded-for),field(3,\,)] if x_forwarded_for_5_ips

让我知道它是否适合您,或者您找到了另一种更好的解决方案:)

编辑:好笑,我甚至花了5分钟才找到更好的解决方案。

使用hdr_ip sample-fetcher: https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#7.3.6-hdr_ip

您仍然需要ACL来计算IP,但您可以直接使用hdr_ip(x-forwarded-for,2)和hdr_ip(x-forwarded-for,3),不需要Field()。< / p>