Skip to content

Instantly share code, notes, and snippets.

@arynyklas
Last active March 11, 2025 23:13
Show Gist options
  • Save arynyklas/c2d13ebbd859383aa04ae61c720dd8eb to your computer and use it in GitHub Desktop.
Save arynyklas/c2d13ebbd859383aa04ae61c720dd8eb to your computer and use it in GitHub Desktop.
Cloudflare Worker to use domain as a proxy to another domain
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