【问题标题】:nginx real client ip not workingnginx真实客户端ip不工作
【发布时间】:2016-12-05 10:02:38
【问题描述】:

我已经安装了 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 设置正确吗?

我怎样才能让它正常工作?

【问题讨论】:

    标签: php curl nginx real-ip


    【解决方案1】:

    经过下面的一些讨论和一些试验/错误,我们发现最好的解决方案是简单地通过 $_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']
    ));
    

    【讨论】:

    • 似乎没有用?当我进一步查看 curl 时,它看起来不会向 site2 php 页面发送标头。 $_SERVER 变量包含 X_CLIENT_REMOTE_IP 变量?
    • 错字:$_SERVER 变量 -doesnt- 包含 X_CLIENT_REMOTE_IP 变量
    • 幽默一下,然后做:print_r(apache_request_headers());。里面有吗?
    • 未捕获错误:调用未定义函数 apache_request_headers()
    • 就个人而言,我认为您应该将其传递到 url,然后将其从 $_GET 中提取出来。 curl_setopt($ch, CURLOPT_URL, $serverUrl . '?client_ip=' . $_SERVER['REMOTE_ADDR']);
    猜你喜欢
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2011-09-02
    • 2020-05-22
    • 2015-06-29
    • 2019-01-01
    • 2022-01-18
    • 2020-08-23
    相关资源
    最近更新 更多