Complex origin-pull URL rewriting
In some business scenarios, you need to modify client request URLs before sending them to the origin server. This example implements two complex URL rewriting scenarios using Edge functions:
1. Path regex replacement: Using regex capture groups for path replacement, replacing paths starting with
/a
with /path-a
while preserving the subsequent path structure. Path regex replacement enables seamless mapping from old paths to new paths, for example when resource directory structures change during content management system updates. Regex capture groups preserve key parts of the original path to ensure content remains accessible while adapting to the new directory structure.2. Path case conversion: Converting the entire path to lowercase, conforming to Web standards best practices. For websites using object storage services (such as Tencent Cloud Object Storage) as their origin, since object storage typically distinguishes between uppercase and lowercase, uniform conversion can simplify resource management and prevent resource access failures due to case sensitivity issues.
Sample Code
async function handleEvent(event) {try {const request = event.request;const url = new URL(request.url);let pathname = url.pathname;// Use regular expression for path replacement, replace /a or /a/xxx with /path-a or /path-a/xxxif (pathname.startsWith('/a')) {const aPathRegex = /^\/a(\/.*)?$/;pathname = pathname.replace(aPathRegex, '/path-a$1');}// Path case conversion, directly convert the entire path to lowercaseif (pathname.startsWith('/b')) {pathname = pathname.toLowerCase();}url.pathname = pathname;// Create a new requestconst newRequest = new Request(url.toString(), {method: request.method,headers: request.headers,body: request.body,redirect: 'manual'});const response = await fetch(newRequest);return event.respondWith(response);} catch (err) {console.log(err);}}addEventListener('fetch', event => {handleEvent(event);});javascript
Example Preview
Enter a URL that matches the Edge function trigger rules in the browser address bar to preview the example effect.
Path regex replacement: Replace paths starting with
/a
with /path-a
, while preserving the subsequent path structure.
Path case conversion: Convert the entire path to lowercase.

Related References