cloudflare 获取真实访问IP

在 http 配置块中添加代码 找到 http { ... } 这个配置段,在它的内部(比如 server_tokens off; 的下一行)添加以下内容:

# ===================================================
# Cloudflare Real IP Configuration
# ===================================================

# 优先从 CF-Connecting-IP Header 获取真实 IP
real_ip_header CF-Connecting-IP;

# (可选,作为备用)如果上面的 Header 不存在,则从 X-Forwarded-For 中获取
# real_ip_header X-Forwarded-For;

# 设置所有 Cloudflare 的 IP 地址段为可信代理
# 只有来自这些 IP 的请求,我们才信任它提供的 real_ip_header
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;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;

# ===================================================

提示: Cloudflare 的 IP 段可能会更新,你可以随时在 Cloudflare 官网 - IP Ranges 页面获取最新的列表。

配置完成后,你的 Nginx 访问日志和后端应用(如 PHP 的 $_SERVER['REMOTE_ADDR'])获取到的就都是用户的真实 IP 了!