Cloudflare 顯示訪客的真實 IP

    內容表格
    1. 1. 說明
    2. 2. 設定開始

    版本為 12:04, 19 Sep 2024

    到這個版本。

    返回到 版本存檔.

    查閱目前版本

    說明

    如果網站有使用 Cloudflare CDN 服務,在 Nginx 的 access.log 紀錄裡只會出現 Cloudflare 的 IP,而無法紀錄所有網站訪客實際的真實 IP 位址。

    這情形對於做網站流量分析會造成訪客來源紀錄不正確的問題,而此篇教學可以解決這問題。

    注意:

    如果網站同時也有作來源 IP 的存取限制,可能會有衝突的現象需注意。

    設定開始

    新增/usr/local/bin/update.cloudflare.ip.sh

    #!/bin/bash
    # A simple shell script update Cloudflares IP addresses.
    # Tested on : Debian and Ubuntu servers and Nginx only
    # ----------------------------------------------------------------------------
    # Author: Vivek Gite 
    # Copyright: 2016 nixCraft under GNU GPL v2.0+
    # ----------------------------------------------------------------------------
    # Last updated 23 Apr 2017
    # ----------------------------------------------------------------------------
    ## source for IPv4 and IPv6 urls ##
    ipf='https://www.cloudflare.com/ips-v4'
    ips='https://www.cloudflare.com/ips-v6'
    
    ## temp file location ##
    t_ip_f="$(/bin/mktemp /tmp/cloudflare.XXXXXXXX)"
    t_ip_s="$(/bin/mktemp /tmp/cloudflare.XXXXXXXX)"
    
    ## nginx config for Cloudflare ##
    conf_out="/etc/nginx/conf.d/cloudflare.real.ip.conf"
    
    ## grab files ##
    /usr/bin/wget -q -O $t_ip_f $ipf
    /usr/bin/wget -q -O $t_ip_s $ips
    
    ## generate it ##
    /usr/bin/awk '{ print "set_real_ip_from " $1 ";" }' $t_ip_f > $conf_out
    /usr/bin/awk '{ print "set_real_ip_from " $1 ";" }' $t_ip_s >> $conf_out
    echo 'real_ip_header CF-Connecting-IP;' >> $conf_out
    
    ## delete temp files ##
    [ -f "$t_ip_f" ] && /bin/rm -f $t_ip_f
    [ -f "$t_ip_s" ] && /bin/rm -f $t_ip_s
    
    ## reload nginx ##
    /bin/systemctl reload nginx
    
    chmod +x /usr/local/bin/update.cloudflare.ip.sh
    

    設定 Nginx
    /etc/nginx/conf.d/<you-web-site>.conf

    ...
    ...
     include "/etc/nginx/conf.d/cloudflare.real.ip.conf";
    

    執行 /usr/local/bin/update.cloudflare.ip.sh

    /usr/local/bin/update.cloudflare.ip.sh
    

    測試網站瀏覽

    檢查 /var/log/nginx/access.log 是否可以顯示訪客的來源 IP

    定期更新

    @weekly /usr/local/bin/update.cloudflare.ip.sh
    
    Powered by MindTouch Core