我安装了 nginx、php7 和 http_realip_module。
我有 1 台服务器,为 2 个网站提供服务。
站点 1 nginx 配置:
server {
...
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_read_timeout 300;
proxy_set_header REMOTE_ADDR $http_x_real_ip;
proxy_set_header X-Forwarded-For $http_x_real_ip;
}
}
当我转储 $_SERVER['REMOTE_ADDR"] 时,这会填充客户端的 IP 地址。
站点 1 使用curl 连接到站点 2,就像简单的 API 一样。
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_URL, $serverUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"REMOTE_ADDR: ".$_SERVER['REMOTE_ADDR'],
"HTTP_X_FORWARDED_FOR: ".$_SERVER['REMOTE_ADDR'],
));
$result = curl_exec($ch);
站点 2 nginx 配置:
server {
...
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_read_timeout 300;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
}
}
我可以看到站点 2 上的脚本被调用,但是当我检查 PHP 中的 $_SERVER['REMOTE_ADDR'] 变量时,它会显示服务器的 IP 地址而不是客户端的 IP 地址。这里的 nginx 设置正确吗?
我怎样才能让它正常工作?
最佳答案
经过下面的一些讨论和一些尝试/错误,我们发现最好的解决方案是简单地通过 $_GET
参数传递它。
尝试使用完全自定义的 header :
curl_setopt($ch, CURLOPT_URL, $serverUrl . '?client_ip=' . $_SERVER['REMOTE_ADDR']);
因为您只是转发此变量,所以实际上没有必要尝试将其定制为 header 。
经过进一步讨论,我发现nginx strips headers with underscores by default 。只需将下划线更改为破折号即可让最终主机获取 header :
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-CLIENT-REMOTE-IP: " . $_SERVER['REMOTE_ADDR']
));
关于php - nginx 真实客户端 ip 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679951/