如上图,今天设置指定IP访问时才注意到这个问题是由于CDN导致,
解决:
(1)在页面https://api.cloudflare.com/client/v4/ips获取CloudFlare的IPV4/V6段:
(2)添加以上网段至nginx.conf或者直接在nginx.conf中引用新的conf文件:
文件内容大致如下:
# Cloudflare IPv4 хпои
set_real_ip_from 173.245.48.0/20;
………………………………………………
# Cloudflare IPv6 хпои
set_real_ip_from 2400:cb00::/32;
………………………………………………………………………………………………………………………………………………
real_ip_header X-Forwarded-For;
在nginx.conf引用:
(3)脚本获取cf的V4/V6地址:
import requests
import os
# 定义 Cloudflare IP API 的 URL
CLOUDFLARE_IP_API = "https://api.cloudflare.com/client/v4/ips"
# 定义输出的 Nginx 配置文件路径
NGINX_CONFIG_PATH = "******/cloudflare_real_ip.conf"
def fetch_cloudflare_ips():
"""从 Cloudflare API 获取 IP 地址列表"""
response = requests.get(CLOUDFLARE_IP_API)
response.raise_for_status()
data = response.json()
ipv4_cidrs = data.get('result', {}).get('ipv4_cidrs', [])
ipv6_cidrs = data.get('result', {}).get('ipv6_cidrs', [])
return ipv4_cidrs, ipv6_cidrs
def write_nginx_config(ipv4_cidrs, ipv6_cidrs):
"""将 IP 地址写入 Nginx 配置文件"""
with open('1.conf', 'w') as f:
f.write("# Cloudflare IPv4 地址\n")
for ip in ipv4_cidrs:
f.write(f"set_real_ip_from {ip};\n")
f.write("\n")
f.write("# Cloudflare IPv6 地址\n")
for ip in ipv6_cidrs:
f.write(f"set_real_ip_from {ip};\n")
f.write("\n")
f.write("real_ip_header X-Forwarded-For;\n")
def reload_nginx():
"""测试并重新加载 Nginx 配置"""
result = os.system("nginx -t")
if result == 0:
os.system("sudo systemctl reload nginx")
else:
print("Nginx 配置测试失败,未重新加载")
def main():
# 获取最新的 Cloudflare IP 地址
ipv4_cidrs, ipv6_cidrs = fetch_cloudflare_ips()
# 写入 Nginx 配置文件
write_nginx_config(ipv4_cidrs, ipv6_cidrs)
# 测试并重新加载 Nginx
#reload_nginx()
if __name__ == "__main__":
main()
(4)设置指定IP访问:
由于已在nginx.conf设置获取这是IP,故无需在子配置文件中进行配置,另一个由于使用CDN,导致直接配置allow及deny无法获取真实IP而失效