この例では、Cloudflare Snippets を使って次を行います。
- 受信リクエストを別のオリジンへ振り分ける
- URL パスの先頭にディレクトリを追加する
- URL パスから特定のセグメントを削除する
export default {
async fetch(request) {
// Clone the original request to create a new request object
const newRequest = new Request(request);
// Add a header to identify a rerouted request at the new origin
newRequest.headers.set("X-Rerouted", "1");
// Clone and parse the original URL
const url = new URL(request.url);
// Step 1: Reroute to a different origin
url.hostname = "example.com"; // Change the hostname to the new origin
// Step 2: Append a directory to the path
url.pathname = `/new-path${url.pathname}`; // Prepend "/new-path" to the current path
// Step 3: Remove a specific segment from the path
url.pathname = url.pathname.replace("/remove-me", ""); // Rewrite `/remove-me/something` to `/something`
// Fetch the modified request from the updated URL
return await fetch(url, newRequest);
},
};この設定では、次のように書き換えます。
| リクエスト URL | 書き換え後の URL |
|---|---|
https://subdomain.example.com/foo |
https://example.com/new-path/foo |
https://example.com/remove-me/bar |
https://example.com/new-path/bar |
https://example.net/remove-me |
https://example.com/new-path |