2 min read

Nginx 與 Cloudflare 協同工作:真實用戶IP 獲取與配置(.conf)

服務器現在都會透過Cloudflare(cf) 進行代理,但進行發現無法取得用戶真實IP,有時候要做些分析也無從下手,所以就順手紀錄了一下。

服務主要都是圍繞在nginx上面, 讓從cf 進來的反向代理都能成功獲續用戶ip,不管Ipv4 或者ipv6。

  1. 需要先讓nginx 知道 cf 有哪些ip網段
    1. 這邊查詢
    2. 將以上配置變成透過nginx 參數 set_real_ip_from 告知nginx 這些網段是屬於cf。
    3. 最後再透過 real_ip_header 指是nginx 從cf 帶來的 HTTP請求頭(header) 之中的 CF-Connecting-IP 獲取用戶的真實IP。
    4. 將以上配置 include 到nginx 內。
set_real_ip_from 173.245.48.0/20;
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 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
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;

real_ip_header CF-Connecting-IP;
  1. nginx.conf 配置/修改 log_format 變成全局參數,可以注意到 user_real_ip 就是使用由上面配置來的header 。
log_format  main  escape=json  
    '{"@timestamp":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status":"$status",'
    '"bytes":$body_bytes_sent,'
    '"referer":"$http_referer",'
    '"user_agent":"$http_user_agent",'
    '"x_forwarded":"$http_x_forwarded_for",'
    '"user_real_ip":"$http_cf_connecting_ip",'
    '"request_time":$request_time}';

之後就可以去 打印 access.log 可以看到 user_real_ip 就是使用者的真實IP。