Cloudflare IP

网站使用 Cloudflare CDN 后,Nginx 的访问日志客户端 IP 是 Cloudflare 转发服务器的代理 IP,并非用户端真实的 IP,获取访客真实 IP 需要额外处理一下,官方文档 处理方法。

获取 Cloudflare 的服务器 IP,生成 real-ip-header 配置文件,并在 Nginx 配置文件的 http {} 适当地方 include 进来即可。

cloudflare-real-ip.sh

#!/usr/bin/env bash

# ----------------------------------------------
# Cloudflare real IP
# cat /opt/scripts/cloudflare-real-ip.sh
# 30 2 * * * cd /opt/scripts && ./cloudflare-real-ip.sh >> /dev/null 2>&1
# ----------------------------------------------

# 脚本错误终止
set -o errexit
# 未定义变量时终止运行
set -o nounset
# 管道子命令失败脚本终止
set -o pipefail
# 输出执行命令
# set -x 
 
CLOUDFLARE_FILE_PATH=/etc/nginx/conf.d/cloudflare.conf
echo "# Cloudflare" > $CLOUDFLARE_FILE_PATH;
echo "" >> $CLOUDFLARE_FILE_PATH;

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

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

echo "" >> $CLOUDFLARE_FILE_PATH;
echo "real_ip_header CF-Connecting-IP;" >> $CLOUDFLARE_FILE_PATH;

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

脚本生成内容

#root@vmiss-hk-y8gkz:/opt/scripts# cat /etc/nginx/conf.d/cloudflare.conf
# Cloudflare
# - IPv4
set_real_ip_from 173.245.48.0/20;
# ...
real_ip_header CF-Connecting-IP;

如果生成文件不是在 /etc/nginx/conf.d/ 目录,请自行修改 /etc/nginx/nginx.conf 文件,使 include 进来。

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    access_log  /var/log/nginx/access.log  main;
    # include your file
    include /etc/nginx/conf.d/*.conf;
}

处理前后 Nginx 日志

# 为处理前 IP 为 Cloudflare IP
172.71.218.203 - - [29/Dec/2023:13:49:33 +0800] "GET /index.html HTTP/1.1" 200 2715 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.1 Mobile/15E148 Safari/604.1"
172.71.218.203 - - [29/Dec/2023:13:49:43 +0800] "GET /2023/2023-10-06-homelab-hardware.html HTTP/1.1" 200 6130 "https://blog.196000.xyz/index.html" "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/1
# 处理后为用户实际 IP
194.99.79.116 - - [31/Dec/2023:11:40:53 +0800] "GET /index.html HTTP/1.1" 304 0 "https://blog.196000.xyz/about.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"

脚本修改自 https://github.com/ergin/nginx-cloudflare-real-ip