内容简介:配置nginx为php-fpm合并多个X-Forwarded-For
最近用阿里云的容器服务遇到一个问题,docker里的 PHP 程序用 X-Forwarded-For
取用户IP的时候,只能取到SLB的地址。经tcpdump抓包确认,是请求经过阿里云的acsrouting的时候,在HTTP请求头中加入了多个 X-Forwarded-For
。查了一下,阿里云用HAProxy做负载均衡服务,又搜了一下HAProxy的资料,发现许多人在用HAProxy时遇到了同类问题,有人给HAProxy提了issue,但对方答复是根据 RFC2616
,多个同名的header和单个逗号分隔列表构成的header是等价的:
Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. The order in which header fields with the same field-name are received is therefore significant to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded.
所以HAProxy不处理已有的 X-Forwarded-For
,只是简单地在header末尾加入一个新的 X-Forwarded-For
。可惜php-fpm对header的处理方式是同名的header只保留最后一个,所以无法取得正确的用户IP。
我找到一个解决方案是让nginx来合并多个 X-Forwarded-For
记录。在 docker 内的nginx配置中加入以下选项(一般在 location ~ \.php$
部分或者在 fastcgi_params
配置文件里):
nginx.conf fastcgi_param HTTP_X_FORWARDED_FOR $http_x_forwarded_for if_not_empty;
配置好之后docker内的nginx服务器就会预先合并多个 X-Forwarded-For
请求header记录为逗号分隔格式,然后再传给php-fpm。
以上所述就是小编给大家介绍的《配置nginx为php-fpm合并多个X-Forwarded-For》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- mysql索引合并:一条sql可以使用多个索引
- .NET 使用 ILMerge 合并多个程序集,避免引入额外的依赖
- .NET 使用 ILRepack 合并多个程序集(替代 ILMerge),避免引入额外的依赖
- 分组字符合并SQL语句 按某字段合并字符串之一(简单合并)
- git 的合并原理(递归三路合并算法)
- git 合并策略
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。