TL; DR
> nginx:fastcgi_param HTTP_MERGED_X_FORWARDED_FOR $http_x_forwarded_for
> php:$_SERVER [‘HTTP_MERGED_X_FORWARDED_FOR’]
说明
您可以使用the $http_ variable访问所有http标头.使用此变量时,nginx甚至会为您执行标头合并
CustomHeader: foo
CustomHeader: bar
获取转换为值:
foo, bar
因此,您需要做的就是将此变量传递给php with fastcgi_param
fastcgi_param HTTP_MERGED_X_FORWARDED_FOR $http_x_forwarded_for
概念证明:
在你的nginx服务器块中:
location ~ \.php${
fastcgi_pass unix:run/php/php5.6-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTP_MERGED_X_FORWARDED_FOR $http_x_forwarded_for;
include fastcgi_params;
}
test.php的
die($_SERVER['HTTP_MERGED_X_FORWARDED_FOR']);
最后看看curl会发生什么:
curl -v -H 'X-Forwarded-For: 127.0.0.1' -H 'X-Forwarded-For: 8.8.8.8' http://localhost/test.php
给出以下回应:
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /test.php HTTP/1.1
> Host: localhost
> User-Agent: curl/7.47.0
> X-Forwarded-For: 127.0.0.1
> X-Forwarded-For: 8.8.8.8
>
< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Wed, 01 Nov 2017 09:07:51 GMT
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
127.0.0.1, 8.8.8.8
繁荣!在那里,您可以访问所有X-FORWARDED-FOR标头,作为$_SERVER中的逗号分隔字符串[‘HTTP_MERGED_X_FORWARDED_FOR’]
当然,您可以使用您想要的任何名称,而不仅仅是HTTP_MERGED_X_FORWARDED_FOR.