使用 EdgeOne CDN 后,若没有更改默认配置,Nginx 将无法获取用户的真实 IP,获取到的全是 CDN 的 IP。
1. 方法一
直接在 Nginx 配置文件 http 块配置:
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
然后重新加载 nginx 配置即可。
2. 方法二(推荐)
该方法源于 NodeSeek 原文链接如下:
https://www.nodeseek.com/post-370347-1
2.1 Nginx 配置
打开 Nginx 配置文件,并在 http 块中添加以下配置:
include /etc/nginx/edgeone.conf;
2.2 新建 Bash 脚本
手动创建一个 Bash 脚本 edgeone-ip-whitelist-sync.sh 内容如下:
#!/bin/bash
EDGEONE_FILE_PATH=${1:-/etc/nginx/edgeone.conf}
echo "#EdgeOne" > $EDGEONE_FILE_PATH;
echo "" >> $EDGEONE_FILE_PATH;
echo "# - IPv4" >> $EDGEONE_FILE_PATH;
for i in `curl -s -L https://api.edgeone.ai/ips?version=v4`; do
echo "set_real_ip_from $i;" >> $EDGEONE_FILE_PATH;
done
echo "" >> $EDGEONE_FILE_PATH;
echo "# - IPv6" >> $EDGEONE_FILE_PATH;
for i in `curl -s -L https://api.edgeone.ai/ips?version=v6`; do
echo "set_real_ip_from $i;" >> $EDGEONE_FILE_PATH;
done
echo "" >> $EDGEONE_FILE_PATH;
echo "real_ip_header EO-Connecting-IP;" >> $EDGEONE_FILE_PATH;
#test configuration and reload nginx
nginx -t && systemctl reload nginx
2.3 执行脚本
chmod +x edgeone-ip-whitelist-sync.sh
./edgeone-ip-whitelist-sync.sh
2.4 输出
得到的 “/etc/nginx/edgeone.conf” 文件如下所示:
#EdgeOne ip addresses
# - IPv4
set_real_ip_from ...;
set_real_ip_from ...;
...
# - IPv6
set_real_ip_from ...;
set_real_ip_from ...;
...
real_ip_header EO-Connecting-IP;
2.5 定时任务 Crontab
EdgeOne 的 IP 地址会每天自动刷新,通过计划任务自动刷新 EdgeOne 的 IP 地址列表,在同步完成后,将重新加载 Nginx。
# Auto sync ip addresses of EdgeOne and reload nginx
30 2 * * * /root/edgeone-ip-whitelist-sync.sh >/dev/null 2>&1