为什么要获取

一般情况下,CDN代理用户返回的请求头中,请求IP会变为CDN节点的,而真实IP放到了另一个键中。导致前端与后端无法获取真实IP,从而引发问题。

如何获取

Cloudflare 为例。

准备

  • NGINX 集成 –with-http_realip_module
  • CDN支持转发真实IP
  • CDN提供CDN节点的IP段

操作步骤

编辑 nginx 的配置文件 ( 通常位于 /usr/local/nginx/conf/nginx.conf )

你也可以放入 conf.d

在HTTP段增加以下代码

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/12;
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;
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 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;
  • set_real_ip_from 为定义需要应用的地址
  • real_ip_header 为替换的键

涉及的IP段可能会变动,请参阅这里

大功告成

现在你应能获取到正确的真实IP了。

分类: Trick

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据