一般在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
有在清單中就是有裝好了!
確認有模組後(缺少的話就要先新增, 這裡先不談)
在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
探索更多來自 哪裡好吃哪裡去:美食避雷箴 的內容
訂閱即可透過電子郵件收到最新文章。