nginx访问日志记录cloudflare后真实ip

使用nginx -V 2>&1 | grep with-http_realip_module,查看nginx是否包含http_realip_module模块,我的ubuntu18 apt安装的nginx已经带有该模块了,那么只需要前往 /etc/nginx/nginx.conf向http{}里面添加如下内容即可。https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses-with-mod-cloudflare-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
use any of the following two

real_ip_header CF-Connecting-IP;

然后重启nginx即可生效

感觉该方法虽然能获取真实ip,但是会丢失一些数据…

分析nginx的access.log访问日志的时候,如果我们使用了cloudflare cdn,我们会发现记录的ip都是cloudflare的节点ip,那么该如何记录真实的访问者ip呢?

nano /etc/nginx/nginx.conf修改nginx的配置文件,在http{}内加入

1
2
3
4
5
6
7
8
map $HTTP_CF_CONNECTING_IP $clientRealIp 
{
    "" $remote_addr;
    ~^(?P<firstAddr>[a-z0-9.:]+),?.*$ $firstAddr;
}
log_format access '$clientRealIp [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '$http_user_agent $remote_addr $request_time';

再在同一文件下的 access_log 末尾加上 access 如 access_log /var/log/nginx/access.log access;.

systemctl restart nginx生效即可。

comments powered by Disqus
本站访客数:
Built with Hugo
主题 StackJimmy 设计