Categories
Nginx

nginx配置cloudflare获取真实客户IP

nginx获取客户真实IP主要场景是前置了至少一级代理,否则默认拿到的就是客户的真实IP

以cloudflare cdn为例,最简单的配置方案是,获取cloud flare的所有cdn的IP放入一个文件,然后加载进nginx配置文件即可

# 获取cloudflare cdn的所有IP,包括IPv4和IPv6
# 脚本如下:

#!/bin/bash
# Author: happylife.page
# Desc  : Update cloudflare cdn IPs
# 

flag=0
cloudflare_url="https://www.cloudflare.com"
real_ip_conf="/etc/nginx/cloudflare_cdn_IPs.conf"

while read ip
do
	grep -q "${ip}" "$real_ip_conf" && continue
	echo "set_real_ip_from $ip;" >> "$real_ip_conf"
	let flag++
done < <(curl ${cloudflare_url}/ips-v4;echo;curl ${cloudflare_url}/ips-v6)

[ $flag -ne 0 ] && echo -e "#-------`date`, ${flag} lines already updated-------#\n" >> "$real_ip_conf"
# nginx你的站点server块里添加:
        include /etc/nginx/cloudflare_cdn_IPs.conf;
	real_ip_header CF-Connecting-IP;

如上脚本执行和nginx配置完成后,nginx -t && nginx -s reload 即可

脚本可以直接丢到计划任务里,每天或每周执行一次足够

Leave a Reply

Your email address will not be published.