Single and Multiple Origin Routing
You can use this document to learn how to create a script that can:
- Re-route a single URL path to a single, alternate origin
- Re-route multiple URL paths to multiple origins
Viewing a Sample Script for a Single Path
In the following example, the route is: /de
This script will apply to all requests that have /de in the path. As a result, after you create a script, you need to ensure that all URLs are accessible, or you can adjust the route and script accordingly.
Review the following sample script:
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
function checkSite(url) {
return new URL(url).pathname.split('/')[1]; // we're checking the URL path, e.g. domain.com/something/else would yield something
}
async function handleRequest(request) {
try {
const path = new URL(request.url).pathname; // we need get the url in order to figure out where to route them
request.url = 'https://domain0.com' + path;
return fetch(request);
} catch (e) {
return new Response(e.stack || e, { status: 500 }); // error handling
}
}
Accessing your Script
You can access your script with any of the delivery domains on your account.
Based on the above example, you can access the script with https://domain.com/de/index, and then the request will be sent to https://domain0.com/de/index.
Viewing a Sample Script for Multiple Paths
In the following example, the route is: *
This script will apply to all requests to your website. As a result, after you create a script, you need to ensure that all URLs are accessible, or you can adjust the route and script accordingly.
Review the following script:
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
function checkSite(url) {
return new URL(url).pathname.split('/')[1]; // we're checking the URL path, e.g. domain.com/something/else would yield something
}
async function handleRequest(request) {
try {
const path = new URL(request.url).pathname; // we need get the url in order to figure out where to route them
switch (checkSite(request.url)) {
case 'de': // if the request is towards the de, e.g. domain.com/de/something
request.url = 'https://domain0.com' + path;
case 'fr': // if the request is towards the fr, e.g. domain.com/fr/something
request.url = 'https://domain1.com' + path;
case 'us': // if the request is towards the us, e.g. domain.com/us/something
request.url = 'https://domain2.com' + path;
}
return fetch(request);
} catch (e) {
return new Response(e.stack || e, { status: 500 }); // error handling
}
}
Accessing your Script
You can access your script with any of the delivery domains on your account.
Based on the above example, you can access the script with https://domain.comde/index, and then the request will be sent to https://domain0.com/de/index.
Updated 30 days ago