nginx真实客户端ip不工作


nginx real client ip not working

我安装了nginx、php7和http_realip_module。

我有一台服务器,为两个网站提供服务。

站点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参数传递它。

尝试使用完全自定义的标题:

curl_setopt($ch, CURLOPT_URL, $serverUrl . '?client_ip=' . $_SERVER['REMOTE_ADDR']);

因为您只是在上转发这个变量,所以实际上没有必要尝试将其定制为标头。

经过进一步的讨论,我发现nginx默认情况下会用下划线来去除头部。只需将下划线更改为短划线,终端主机就可以获得标题:

curl_setopt($ch, CURLOPT_HTTPHEADER, array( 
    "X-CLIENT-REMOTE-IP: " . $_SERVER['REMOTE_ADDR']
));