我安装了nginx,php7和http_realip_module。
我有1台服务器,提供2个网站。
site 1 nginx config:
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);
site 2 nginx config:
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设置是否正确?
我怎样才能让它正常工作?
答案 0 :(得分:2)
经过一些讨论和下面的一些试验/错误后,我们发现最佳解决方案是简单地将其传递给$_GET
参数。
尝试使用完全自定义的标头:
curl_setopt($ch, CURLOPT_URL, $serverUrl . '?client_ip=' . $_SERVER['REMOTE_ADDR']);
因为您只是简单地转发此变量,所以不一定要尝试将其定制为标题。
经过进一步讨论后,我发现nginx strips headers with underscores by default。只需将下划线更改为破折号即可让终端主机获取标题:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-CLIENT-REMOTE-IP: " . $_SERVER['REMOTE_ADDR']
));