Skip to content

Instantly share code, notes, and snippets.

@amitsaxena
Last active March 10, 2021 01:53
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 amitsaxena/719e20fd0185b7e02377bbf029213947 to your computer and use it in GitHub Desktop.
Save amitsaxena/719e20fd0185b7e02377bbf029213947 to your computer and use it in GitHub Desktop.
Cloudflare worker to proxy requests (any HTTP method) to a different origin
const base = "https://newsubdomain.example.com"
async function handleRequest(request) {
// Make a copy to allow mutation.
request = new Request(request);
// To override default caching mechanism and respect Cache-Control.
request.cf.cacheEverything = true;
// Extract path from request URL.
const url = new URL(request.url);
const { pathname, search } = url;
const originUrl = base + pathname + search;
const response = await fetch(originUrl, request);
return response;
}
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