Last active
August 9, 2024 19:40
-
-
Save mplacona/fda91b62c33b6cb7d34808a2e0cf9ffb to your computer and use it in GitHub Desktop.
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) | |
// Check if the path starts with /blog | |
if (url.pathname.startsWith('/blog')) { | |
const subPath = url.pathname.replace('/blog', '') | |
const githubUrl = new URL(`SOURCE_URL${subPath}`) | |
try { | |
const response = await fetch(githubUrl) | |
// Handle errors | |
if (!response.ok) { | |
return new Response(`Page not found: ${url.pathname}`, { status: 404 }) | |
} | |
const contentType = response.headers.get('Content-Type') || '' | |
// Handle HTML content | |
if (contentType.includes('text/html')) { | |
const text = await response.text() | |
const rewrittenText = text.replace(SOURCE_URL/g, 'DESTINATION_URL/blog') | |
const newResponse = new Response(rewrittenText, response) | |
// Set headers | |
newResponse.headers.set('Content-Type', contentType) | |
newResponse.headers.set('Location', url.toString()) | |
newResponse.headers.set('Cache-Control', 'public, max-age=3600') | |
newResponse.headers.set('X-Content-Type-Options', 'nosniff') | |
newResponse.headers.set('X-Frame-Options', 'DENY') | |
newResponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin') | |
newResponse.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload') | |
return newResponse | |
} | |
// Handle non-HTML content (like images) | |
else { | |
const newResponse = new Response(response.body, response) | |
newResponse.headers.set('Cache-Control', 'public, max-age=3600') | |
return newResponse | |
} | |
} catch (error) { | |
console.error(`Error fetching content: ${error}`) | |
return new Response('An error occurred', { status: 500 }) | |
} | |
} else { | |
// Pass through requests not starting with /blog | |
return fetch(request) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Its nice Thanks