php - nginx 真实客户端 ip 不起作用

标签 php curl nginx real-ip

我安装了 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/

相关文章:

nginx - 仅当安装了模块时才在 nginx.conf 中应用指令(apache ifmodule 替代方案)

php - 在 PHP 中匹配非负整数的正则表达式?

php - 在多个文件夹php上上传图像

php - 从 PHP CURL 使用 FTP

php - 加载 php 模块时出错

nginx - 设置 Linode(Ubuntu 10.04 32 位)nginx 未启动。 98 : address already in use

php - 从mysql表中检索数据时如何忽略空格

php - 我需要一些专家关于如何使用 MySQL 开发 PHP 站点的建议

php - 警告 file_get_contents() 无法打开流 : HTTP request failed! HTTP/1.0 402 需要付款

post - 当 POST 从 http 重定向到 https 时,Curl 丢失正文