当使用 Cloudflare 作为网站的 CDN(内容分发网络)时,为了获取真实客户端 IP 地址,我们可以使用 NGINX 的 ngx_http_realip_module 模块。该模块允许我们将 Cloudflare 的真实 IP 地址传递给后端服务器,以便正确识别客户端的来源。

下面是一个示例的 NGINX 配置,展示了如何使用 ngx_http_realip_module 模块和 Cloudflare 的 IP 地址列表来获取真实客户端 IP 地址:

http {
    # 启用 ngx_http_realip_module 模块
    real_ip_header CF-Connecting-IP;
    #real_ip_header X-Forwarded-For;

    # 设置 Cloudflare 的 IP 地址段
    set_real_ip_from 173.245.48.0/20;
    set_real_ip_from 103.21.244.0/22;
    set_real_ip_from 103.22.200.0/22;
    set_real_ip_from 103.31.4.0/22;
    set_real_ip_from 141.101.64.0/18;
    set_real_ip_from 108.162.192.0/18;
    set_real_ip_from 190.93.240.0/20;
    set_real_ip_from 188.114.96.0/20;
    set_real_ip_from 197.234.240.0/22;
    set_real_ip_from 198.41.128.0/17;
    set_real_ip_from 162.158.0.0/15;
    set_real_ip_from 104.16.0.0/13;
    set_real_ip_from 104.24.0.0/14;
    set_real_ip_from 172.64.0.0/13;
    set_real_ip_from 131.0.72.0/22;

    # 其他 NGINX 配置项...
    # ...

    server {
        # 服务器配置项...
        # ...
    }

    # 其他 server 块...
    # ...

    # 重新加载配置使更改生效
    # sudo systemctl reload nginx
}

在这个示例配置中,我们将 ngx_http_realip_module 模块添加到 NGINX 配置中,并配置了 Cloudflare 的 IP 地址段。使用 real_ip_header 指令来指定使用 CF-Connecting-IP 请求头来获取真实客户端 IP 地址。你也可以选择使用 X-Forwarded-For 请求头。

确保将示例配置中的 Cloudflare IP 地址列表进行定期更新,以包含最新的 IP 地址段。你可以从 https://www.cloudflare.com/ips/ 获取最新的 Cloudflare IP 地址列表。

最后,重新加载 NGINX 配置以使更改生效,可以使用命令 sudo systemctl reload nginx

通过使用 ngx_http_realip_module 模块和配置 Cloudflare 的 IP 地址段,我们可以在 NGINX 中准确获取到真实的客户端 IP 地址,从而为我们的应用程序提供正确的访问来源信息。

希望这篇博客文章对你有所帮助!如果有任何问题或疑惑,请随时提问。

最后修改:2023 年 07 月 11 日
如果觉得我的文章对你有用,请随意赞赏