Skip to content

Instantly share code, notes, and snippets.

@longseespace
Last active September 15, 2024 04:01
Show Gist options
  • Save longseespace/12b6ada2b0f3b20f9afc488280cea648 to your computer and use it in GitHub Desktop.
Save longseespace/12b6ada2b0f3b20f9afc488280cea648 to your computer and use it in GitHub Desktop.
Cloudflare Worker Proxy
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const { pathname, search } = url;
var newPathname = pathname;
if (pathname.startsWith('/docs')) {
newPathname = pathname.replace('/docs', '');
}
const originUrl = `https://docs.boltai.com${newPathname}${search}`;
console.log('originUrl', originUrl);
const fetchOptions = {
method: request.method,
headers: request.headers,
redirect: 'follow', // Ensure redirects are followed
};
const response = await fetch(originUrl, fetchOptions);
// Check if the response is HTML
const contentType = response.headers.get('content-type');
if (contentType && (contentType.includes('text/html') || (contentType.includes('text/css')))) {
// Get the response text
let text = await response.text();
// Replace the script sources
text = text.replace(
/\/_next\/static/g,
'https://boltai.com/docs/_next/static'
);
// Replace the canonical link
text = text.replace(
/<link rel="canonical" href="https:\/\/docs\.boltai\.com\/docs/g,
'<link rel="canonical" href="https://boltai.com/docs'
);
// Create a new response with the modified HTML
const newResponse = new Response(text, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
return newResponse;
}
// If not HTML, return the original response
return response;
}
@jasonleow
Copy link

Oh I remember this! Thanks for the full code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment