NGINX 服务器使用 CloudFlare 代理后获取访客真实 IP

 Technique  comment

前言

NGINX 服务器使用 CloudFlare 后,日志中只能抓取到 CF 的代理 IP ,并不是用户的真实地址。

解决

在 NGINX 的配置文件中添加以下参数即可(HTTP 段)

include /etc/nginx/cloudflare;

然后写入脚本

#!/bin/bash
echo "#CloudFlare IP Addresses Pool" > /etc/nginx/cloudflare;
echo "" >> /etc/nginx/cloudflare;

echo "# - IPv4" >> /etc/nginx/cloudflare;
for i in `curl https://www.cloudflare.com/ips-v4`; do
    echo "set_real_ip_from $i;" >> /etc/nginx/cloudflare;
done

echo "" >> /etc/nginx/cloudflare;
echo "# - IPv6" >> /etc/nginx/cloudflare;
for i in `curl https://www.cloudflare.com/ips-v6`; do
    echo "set_real_ip_from $i;" >> /etc/nginx/cloudflare;
done

echo "" >> /etc/nginx/cloudflare;
echo "real_ip_header CF-Connecting-IP;" >> /etc/nginx/cloudflare;

#test configuration and reload nginx
nginx -t && systemctl reload nginx

注意:请手动执行此脚本即可生成配置文件,若目录不一致请修改为实际环境。

附录

参考链接

回复