I had a scenario where I had to use a cloudflare worker to redirect one page to another, but, I also had to do the following:
- Display a nice website saying “We will redirect you shortly” with a nice company logo
- The original and destination URL segments has to be kept in tact.
- For example, if the source URL is https://sourceurl.com/a/b/c?d=123 the destination URL must be https://destinationurl.com/a/b/c?d=123
Cloudflare Worker Code
- First we get the URL segments and query parameters from our incoming URL
- Then we build a new URL using those segments and query parameters
Apart from the above, the following will be useful as well:
- Send back a no-cache header
- Look up a value from a Worker KV (Cloudflare’s keystore). For this to work, remember to bind the worker to the keystore. You do this in the worker settings
- This is needed to e.g. check what the first URL segment is, and look up a value where you should redirect to for dynamic redirects
Then we create our DNS A record if we have to.
Then we assign this worker to this new DNS record