Skip to content

Instantly share code, notes, and snippets.

@hoangddt
Forked from longseespace/worker.js
Created August 1, 2024 07:41
Show Gist options
  • Save hoangddt/5de2e44935029fd8c353e02b257306b0 to your computer and use it in GitHub Desktop.
Save hoangddt/5de2e44935029fd8c353e02b257306b0 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment