You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nginx sites-available配置中改用请求头IP做访问控制

针对单个Nginx站点基于Cloudflare True-Client-IP做IP限制的配置方案

直接实现方案(无需维护Cloudflare IP列表)

在你的website123.com站点配置文件的server块内部,添加真实IP解析配置,保留原有的allow/deny规则即可:

server {
    listen 80;
    server_name website123.com;

    # 配置当前站点使用Cloudflare的True-Client-IP作为客户端真实IP
    set_real_ip_from 0.0.0.0/0;
    realip_header True-Client-IP;
    realip_recursive on;

    location / {
        # 原有的IP限制规则不变
        allow 123.123.123.124;
        allow 123.123.123.125;
        allow 123.123.123.126;
        deny all;

        # 其他location配置示例
        root /var/www/website123;
        index index.html;
    }
}

注意事项

  • set_real_ip_from 0.0.0.0/0会信任所有来源的True-Client-IP头,存在安全风险:若攻击者绕过Cloudflare直接访问服务器,伪造该请求头即可绕过IP限制。
  • 确保你的Nginx已编译ngx_http_realip_module模块(主流Linux发行版的官方Nginx包默认包含该模块)。

更安全的方案(自动维护Cloudflare IP列表)

若要兼顾安全又避免手动维护IP列表,可通过脚本定期拉取Cloudflare官方IP段,自动更新Nginx配置片段:

  1. 创建单独配置文件/etc/nginx/cloudflare-ips.conf,用于存储Cloudflare IP段
  2. 编写自动更新脚本:
#!/bin/bash
curl -s https://www.cloudflare.com/ips-v4 | sed 's/^/set_real_ip_from /;s/$/;/' > /etc/nginx/cloudflare-ips.conf
curl -s https://www.cloudflare.com/ips-v6 | sed 's/^/set_real_ip_from /;s/$/;/' >> /etc/nginx/cloudflare-ips.conf
nginx -t && systemctl reload nginx
  1. 给脚本添加执行权限,通过cron定期运行(例如每天一次)
  2. 修改站点配置,替换set_real_ip_from 0.0.0.0/0为:
include /etc/nginx/cloudflare-ips.conf;

此方案仅信任Cloudflare发来的请求解析True-Client-IP,且无需手动维护IP列表。

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:20:24