Last active
March 10, 2021 01:53
-
-
Save amitsaxena/719e20fd0185b7e02377bbf029213947 to your computer and use it in GitHub Desktop.
Cloudflare worker to proxy requests (any HTTP method) to a different origin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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