使用 CDN 后如果不进一步配置,那么 nginx 就难以获取访问者的真实 IP,使用 ngx_http_realip_module 可以方便的获取到这个 IP.

使用下面的命令查看你的 nginx 是否已经安装了 ngx_http_realip_module:

nginx -V 2>&1 | tr ' ' '\n' | grep realip

如果回显

--with-http_realip_module
--with-stream_realip_module

则已经安装 ngx_http_realip_module,没有的话可能需要自己重新编译。

/etc/nginx/conf.d/ 下创建文件 set_real_ip.conf,输入如下内容:

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 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
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 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;

real_ip_header X-Forwarded-For;

检查语法是否正确:

sudo nginx -t

重新加载配置文件:

sudo nginx -s reload

Cloudflare 的 IP 池可能会发生改变,你可能需要编写一个脚本来监听并自动配置。这是脚本所用到的 API文档