使用Nginx、Angular和Spring Boot无法获取客户端真实IP求助
解决Nginx反向代理下Spring Boot无法获取客户端真实IP的问题
当前配置的核心问题
- 注释掉了
X-Forwarded-For头,这是传递客户端IP链的关键字段 CF-Connecting-IP头赋值错误:Cloudflare会直接在请求头中携带CF-Connecting-IP字段存储客户端真实IP,不应使用$proxy_add_x_forwarded_for赋值- 未配置Nginx信任Cloudflare的IP段,导致
$remote_addr始终获取的是Cloudflare节点IP,而非客户端真实IP
修正后的Nginx配置
第一步:在http块中添加Cloudflare IP信任规则
Cloudflare的官方IP段会定期更新,以下是当前通用的IP段配置(需保持同步更新):
http { # 信任Cloudflare的IPv4段 set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 104.16.0.0/13; set_real_ip_from 104.24.0.0/14; set_real_ip_from 108.162.192.0/18; set_real_ip_from 131.0.72.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 162.158.0.0/15; set_real_ip_from 172.64.0.0/13; set_real_ip_from 173.245.48.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 190.93.240.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; # 信任Cloudflare的IPv6段 set_real_ip_from 2400:cb00::/32; set_real_ip_from 2606:4700::/32; set_real_ip_from 2803:f800::/32; set_real_ip_from 2405:b500::/32; set_real_ip_from 2405:8100::/32; set_real_ip_from 2a06:98c0::/29; set_real_ip_from 2c0f:f248::/32; # 指定从Cloudflare的CF-Connecting-IP头获取真实IP real_ip_header CF-Connecting-IP; real_ip_recursive on; # 原有http块配置... include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; ssl_certificate ./ssl/my-sert.crt; ssl_certificate_key ./ssl/my-key.key; upstream apispring { server 127.0.0.1:8080; } server { listen 443 ssl; server_name apis.sad.com; proxy_set_header Host $host; # 传递真实IP到后端 proxy_set_header X-Real-IP $realip_remote_addr; # 传递完整的IP链 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 保留Cloudflare的原始IP头 proxy_set_header CF-Connecting-IP $http_cf_connecting_ip; location / { proxy_pass http://apispring; } } }
Spring Boot端配置
需要让Spring Boot识别反向代理传递的IP头,在application.properties或application.yml中添加:
# 启用框架级别的转发头处理 server.forward-headers-strategy=framework
如果是Spring Boot 2.2以下版本,使用:
server.use-forward-headers=true
测试注意事项
- 确保请求确实经过Cloudflare:本地测试时,需通过域名
apis.sad.com访问(而非直接IP),且DNS解析由Cloudflare处理 - 手机测试需使用移动数据(而非本地WiFi),VPN需连接到外部网络,避免请求直接进入本地局域网绕过Cloudflare
内容的提问来源于stack exchange,提问作者Jackie Chan
相关产品推荐
相关产品推荐

