-
-
Save ideabrian/82ecc5414c782a353491d784a17d706b to your computer and use it in GitHub Desktop.
Cloudflare Worker Proxy
This file contains 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
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