Last active
March 11, 2025 23:13
-
-
Save arynyklas/c2d13ebbd859383aa04ae61c720dd8eb to your computer and use it in GitHub Desktop.
Cloudflare Worker to use domain as a proxy to another domain
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
export default { | |
async fetch(request, env, ctx) { | |
let url = new URL(request.url); | |
url.hostname = url.hostname.replace(/\.?src\.com$/, '.dest.com'); | |
let newHeaders = new Headers(request.headers); | |
newHeaders.set('Host', url.hostname); | |
let newRequest = new Request(url.toString(), { | |
method: request.method, | |
headers: newHeaders, | |
body: request.body, | |
redirect: 'manual', | |
cf: request.cf, | |
}); | |
let response = await fetch(newRequest); | |
// Clone the response to modify headers if needed | |
let modifiedResponse = new Response(response.body, response); | |
// Example: Modify the 'Location' header in redirects | |
if (response.status >= 300 && response.status < 400 && response.headers.has('Location')) { | |
let location = response.headers.get('Location'); | |
location = location.replace(/\.?src\.com$/, '.dest.com'); | |
modifiedResponse.headers.set('Location', location); | |
} | |
return modifiedResponse; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment