Skip to content

Instantly share code, notes, and snippets.

@natanavra
Created January 2, 2024 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natanavra/4faea50655cc7ee558bc3fd35c68d2d6 to your computer and use it in GitHub Desktop.
Save natanavra/4faea50655cc7ee558bc3fd35c68d2d6 to your computer and use it in GitHub Desktop.
cloudflare worker code for proxying requests on a subdirectory
const sourceDomain = 'blog.shapo.io';
async function handleRequest(request) {
const parsedUrl = new URL(request.url)
console.log('url:', request.url, 'parsed:', parsedUrl.toString());
// if its blog html, get it
if(parsedUrl.pathname.includes('/blog')) {
parsedUrl.hostname = sourceDomain;
parsedUrl.pathname = parsedUrl.pathname.replace('/blog', '');
console.log('requesting:', parsedUrl.toString());
const response = await fetch(parsedUrl, request);
return response;
}
console.log("this is a request to my root domain", parsedUrl.host, parsedUrl.pathname);
// if its not a request blog related stuff, do nothing
return fetch(request)
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment