I have two servers: server in Europ S-eu with IP 1.1.1.1 and server in U.S. S-us with IP 2.2.2.2
Traffic for main domain mydomain.com goes to server S-eu, traffic for subdomain en.mydomain.com goes to server S-us.
But I want to delete subdomain and route traffic based on URL, URLs that contains “/en/” go to server S-us all other URLs go to server S-eu.
But I get Plesk login page with this IP 2.2.2.2, but in DNS Records this IP is set for subdomain on S-us server.
I guess this has something to do with proxy.
How should I solve this problem.
Response.redirect creates an HTTP Response that redirects the user to the destination URL, i.e they would go to https://2.2.2.2 in their browser. Probably not what you would want.
You can absolutely use Workers to do this though. Keep in mind Workers can only fetch/use domains though, not raw IP Addresses. You could do something simple like:
// Function to handle routing based on the path
async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname;
// Check if the path starts with /en/
if (path.startsWith('/en/')) {
const usURL = new URL('https://en.example.com' + path);
return fetch(usURL, request);
} else {
// if it the worker is running as a route over the apex, you could just use
// return fetch(request);
const euURL = new URL('https://eu.example.com' + path);
return fetch(euURL, request);
}
}
// Export the fetch event listener
export default {
async fetch(request, env) {
return await handleRequest(request);
},
};
Cloudflare also offers a managed Load Balancer addon that takes care of this all for you. You can steer based on geo coordinates, or with Traffic Steering addon, dynamically, based on countries, etc.
Thank you for your reply.
I understand your solution, but my problem is that I want to get rid of the subdomain.
I want to have only one main domain on both servers.
I want to delete the subdomain and route traffic based on the URL, but the difference between the two cases is only in the path.
if (path.startsWith(‘/en/’)) {
const URL = new URL(‘https ://example.com’ + path);
} else {
const URL = new URL(‘https ://example.com’ + path);
}
How can I route traffic to the U.S. server (IP 2.2.2.2) in the first case and to the Europe server (IP 1.1.1.1) in the second case.
The example worker I gave would do that. If you deployed a worker like that on your apex (example.com), it would send traffic en.example.com if the path started with /en/, otherwise traffic would go to eu.example.com. The end-user wouldn’t see the other server URLs at all, the worker itself is doing the requests and returning the results.
Your actual origins would see the traffic as coming from en/eu.example.com and have to be configured for traffic from that.
Again, you can pay for the Load Balancer addon and get this same behavior without having to manage the worker/any other code.