Hi there -
We’d like to set up a service worker to forward all requests from a domain, let’s say domain1.com to a different domain, let’s say domain2.com while keeping the path and parameters and showing the domain1.com url in the browser.
So, if a user goes to https://domain1.com/path?par=something, the browser should actually show content from https://domain2.com/path?par=something but the URL should show https://domain1.com/path?par=something.
Is that feasible? Appreciate any help!
I think this example from the Cloudflare Workers Examples section might be what you want.
Hi, then how to rewrite the canonical too?
thank you! Any idea how to retain the path & parameters? I believe the linked example just shows a static url (https://example.com) no matter what original url the user navigates to
You want to preserve the path, parameters, and hash but change the domain (hostname). Try this:
const URL = new URL(request.url);
URL.host = 'domain2.com';
const fetchResponse = fetch(URL, request);
Whats happening in that code snippet is your first preparing the new URL to fetch from. That new URL is the same as the request URL except for the domain being swapped from domain1.com to domain2.com
And then doing a fetch of the resource from that new domain whilst preserving the headers from the original request.