Skip to content

Commit d61ba38

Browse files
committed
[Snippets] New example: Change origin and modify paths
1 parent 46a6792 commit d61ba38

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
---
2+
type: example
3+
summary: Reroute a request to a different origin and modify the URL path.
4+
goal:
5+
- Routing
6+
operation:
7+
- Modify URL
8+
products:
9+
- Snippets
10+
pcx_content_type: example
11+
title: Change origin and modify paths
12+
description: Route requests to a different origin, prepend a directory to the URL path, and remove specific segments.
13+
---
14+
15+
This example demonstrates how to use Cloudflare Snippets to:
16+
17+
* Reroute incoming requests to a different origin.
18+
* Prepend a directory to the URL path.
19+
* Remove specific segments from the URL path.
20+
21+
```js
22+
export default {
23+
async fetch(request) {
24+
// Clone the original request to create a new request object
25+
const newRequest = new Request(request);
26+
27+
// Add a header to identify a re-routed request at the new origin
28+
newRequest.headers.set("X-Rerouted", "1");
29+
30+
// Clone and parse the original URL
31+
const url = new URL(request.url);
32+
33+
// Step 1: Reroute to a different origin
34+
url.hostname = "example.com"; // Change the hostname to the new origin
35+
36+
// Step 2: Append a directory to the path
37+
url.pathname = `/new-path${url.pathname}`; // Prepend "/new-path" to the current path
38+
39+
// Step 3: Remove a specific segment from the path
40+
url.pathname = url.pathname.replace("/remove-me", ""); // Rewrite `/remove-me/something` to `/something`
41+
42+
// Fetch the modified request from the updated URL
43+
return await fetch(url, newRequest);
44+
}
45+
};
46+
```
47+
48+
This configuration will perform the following rewrites:
49+
50+
| Request URL | URL after rewrite |
51+
| ----------------------------------------- | ---------------------------------- |
52+
| `https://subdomain.example.com/foo` | `https://example.com/new-path/foo` |
53+
| `https://example.com/remove-me/bar` | `https://example.com/new-path/bar` |
54+
| `https://example.net/remove-me` | `https://example.com/new-path/` |

0 commit comments

Comments
 (0)