I set up a reverse proxy for my blog with the following Cloudflare worker code:
const DOMAIN = 'wunderstock.com'; //
const PROXYPATH = 'blog'; // path to be proxied
const ORIGIN = 'blog.wunderstock.com'; // where to fetch content from
addEventListener('fetch', event => {
var url = new URL(event.request.url);
if (url.pathname.startsWith('/' + PROXYPATH + '/') || url.pathname === '/' + PROXYPATH) {
handleRequest(event, url);
} else {
event.respondWith(fetch(event.request));
}
})
async function handleRequest(event, url) {
// Change URL from public URL to use the origin URL
var originUrl = url.toString().replace(
'https://' + DOMAIN + '/' + PROXYPATH,
'https://' + ORIGIN
);
event.passThroughOnException();
event.respondWith(fetch(originUrl));
}
Now I want to set up a 301 redirect from blog.wunderstock.com/* to wunderstock.com/blog/*. I’ve tried this via Page Rules and locally. I run into the following issues:
-
Local 301 redirects loop infitinity, ie you will end up with wunderstock.com/blog/wunderstock.com/blog/wunderstock.com/blog/… as the final address
-
Page Rules for the redirect simply don’t activate. I assume this is because the worker takes precedence, but I don’t know how to integrate a redirect into the worker.
What the best way to integrate a redirect given my worker setup?
Additionally, is there a way to have the worker also add a trailing slask to any URLs where it is missing?