nginx实际客户端ip不能正常工作

问题描述:

我安装了nginx,php7和http_realip_module。nginx实际客户端ip不能正常工作

我有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“]

网站1使用curl像一个简单的API连接到站点2此填入客户端的IP地址。

$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 strips headers with underscores by default。简单地将下划线改为破折号允许最终主机得到标题:

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

似乎没有工作?当我进一步看卷曲时,它看起来并没有将标题发送到site2 php页面。 $ _SERVER变量是否包含X_CLIENT_REMOTE_IP变量? – Ourx

+0

您是否尝试过只是在执行'print_r($ _ SERVER);'? – FrankerZ

+0

错字:$ _SERVER变量-doesnt-包含X_CLIENT_REMOTE_IP变量 – Ourx