使用 Nginx 設定通過 Cloudflare 的真實 IP 與只允許 Cloudflare IP 來的流量。

一次講兩件事,都是和 Cloudflare 的 IP 有關。

首先是在Ngnix 中,設定只允許 Cloudflare IP 來的流量。幾點注意:

  1. 需確認 Nginx 設定的網域有沒有通過 Cloudflare 的 Proxy,也就是看 DNS 設定中,橘色的雲有沒有亮起。
  2. 一樣的設定可以套用在其他有 Proxy/VPN/CDN 等操作上。組合拳是:流量走我的,其他檔下來。
  3. 同樣的組合拳也可以設定在單一允許 ip 的 api service 上面,不過請注意邏輯層與系統層的拆分,別被自己的 code 搞死了。
  4. Cloudflare 的 ips 是會更新的,請參考這裡
  5. 如果你有用 crontab 執行 url 的話記得也要把 allow 補進去。例如: allow 127.0.0.1; 或是改成 cli 的操作(推薦)。
allow 173.245.48.0/20;
allow 103.21.244.0/22;
allow 103.22.200.0/22;
allow 103.31.4.0/22;
allow 141.101.64.0/18;
allow 108.162.192.0/18;
allow 190.93.240.0/20;
allow 188.114.96.0/20;
allow 197.234.240.0/22;
allow 198.41.128.0/17;
allow 162.158.0.0/15;
allow 104.16.0.0/13;
allow 104.24.0.0/14;
allow 172.64.0.0/13;
allow 131.0.72.0/22;

allow 2400:cb00::/32;
allow 2606:4700::/32;
allow 2803:f800::/32;
allow 2405:b500::/32;
allow 2405:8100::/32;
allow 2a06:98c0::/29;
allow 2c0f:f248::/32;

deny all; # deny all remaining ips

再來是設定讓網站在通過 Cloudflare 之後,可以獲取到真實 ip 的設定,這部分我是抄網路的,有些覺得怪的地方,如果有理解錯誤還煩請指正。

  1. set_real_ip_from 是指信任的 proxy ip 所以要設定為 cloudflare 的 ip 段,標示這些來源的 ip 才能正確取得真實的 client ip。
  2. real_ip_header 是修改真實 ip 的 header 字段,默認是 X-Real-IP。改為 CF-Connecting-IP 是 cloudflare 在邊緣到您的來源 Web 伺服器的流量上傳送的標頭。請參考 Cloudflare 文件
  3. 上面提到的流量來源限制和 set_real_ip_from 的設置會衝突,不能一起設置 🫠
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;

#use any of the following two

real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For; # 滿多人用這個,不過 cf 有自己比較安全的標頭。

同場加映 Cloudflare 的 ips 清單,更新頻率不高,不過設定上幾個注意:

  1. 相關 ips 的設定儘量統一管理。
  2. 有提供 api 可呼叫,參考這裡,如果要做自動化的人可以來弄弄。

已發佈

分類:

作者: