【數位3C】解決使用Cloudflare CDN與Nginx無法正常顯示來源IP的問題

【數位3C】解決使用Cloudflare CDN與Nginx無法正常顯示來源IP的問題 3C/資訊/通訊/網路 Linux Windows 架站 靈異現象&疑難雜症

一般在nginx要看到來源IP只要在設定檔內加上

proxy_set_header Host $host; 

proxy_set_header X-Real-IP $remote_addr; 

proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;

 

不過如果你搭配使用了cloudflare這類的CDN就可能會失效

以nginx來說, 透過with-http_realip_module 模組與修改設定可以解決這個問題

首先透過nginx -V

檢查nginx 模組有無缺少–with-http_realip_module

有在清單中就是有裝好了!

【數位3C】解決使用Cloudflare CDN與Nginx無法正常顯示來源IP的問題 3C/資訊/通訊/網路 Linux Windows 架站 靈異現象&疑難雜症

 

確認有模組後(缺少的話就要先新增, 這裡先不談)

在nginx.conf內的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/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;
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;
#real_ip_header X-Forwarded-For;

加好後使用nginx -t檢查有無錯誤

沒錯的話reload重啟即可

 

IP清單需要手動定期更新

可參考官方清單 IP Ranges | Cloudflare

 

請多指教, 有什麼想法都可以說