Skip to main content

Command Palette

Search for a command to run...

Cloudflare Page Rules Migration Notes (w/ Forwarding URL)

Updated
2 min read
Cloudflare Page Rules Migration Notes (w/ Forwarding URL)
H

Kubernetes & Platform Engineering (DevOps Worker)

Cloudflare 即將在 2024/07 開始進行 Page Rules 的棄用計畫,預計 2025 年會轉移完成。如果本身有使用 Cloudflare Page Rules 的人,你應該要準備將相關的設定轉移到新的 Redirect Rules 中。

相關的公告如下: [ref]

Page Rules migration guide

Cloudflare Page Rules are deprecated. For new Cloudflare accounts and zones, Page Rules will stop being available on Free plans from 2024-07-01 onward (refer to Relevant dates for information on other plans). For existing accounts and zones, the creation of new Page Rules will no longer be available from 2025-01-06 onward, and existing rules will be migrated to different Rules features throughout 2025. This change will affect customers using the Cloudflare dashboard, the Cloudflare APIOpen API docs link, and the Cloudflare Terraform providerOpen external link.

Cloudflare recommends that you start transitioning from Page Rules to our new Rules features immediately by following the recommendations in this migration guide.

根據公告內容,官方已針對所有 Page Rules 可能遇到的情況詳細說明,並提供了轉移方案。但實際在轉移至新版過程中,我還是有遇到一些問題,特別是在 Forwarding URL 的設定上。今天會針對此部分紀錄一下我是怎麼操作的。


原始需求

Cloudflare Page Rule Setting:

  • URL: 0w0.meme/

  • Destination URL: https://$1google.com/$2

這樣子的設定代表只要從 0w0.meme 進來的所有的流量,都會再將子網域帶到新的 google.com 中並 301 跳轉掉。


設定過程

根據 Cloudflare 提供的 Rulesets 文件 [ref],可以看到建議的調整方法只針對 www -> @ 的寫法,沒有動態根據子域名去做跳轉的教學。就算是 Rulesets Function 文件 [ref] 也僅有提到可以使用 substring、regex_replace 的方式處理,但沒告訴你的是:

  1. regex_replace 方法需要付費帳號才可以使用。

  2. substring 不能在裡面再放雙重函數如 len 去計算域名長度,來達成自動化依據域名長度去取得子域名。

那實際上要怎麼處理?

substring 在文件有說到 The end index must be greater than the start index,代表你帶的值只能是像 substring(http.request.body.raw, 2, 5) 這樣或是 substring(http.request.body.raw, -2),這些提供的方法並不能達成只取得子網域的目的。而他沒講到的是你可以其實可以用負值的方法,去撈取到前面的字串。

比如我的網址是 0w0.meme,你可以使用 substring(http.host, 0, -8) 去取得帶入的子域名,而這個規則就跟一開始提到的 end index 一定要大於 start index 是不符合的。

如果加上 concat 語法你就可以這樣寫:

concat("https://", substring(http.host, 0, -8), "google.com", http.request.uri.path)

這樣就可以達成到自動依據子域名,帶入到其他域名進行跳轉的功能。以上就是 Page Rules with Forwarding URL 設定的方法,至於其他的你可以到他們官方網站查看了解。

祝各位轉移順利!