Created
February 8, 2019 18:29
-
-
Save shikhir-arora/792b8d48ca562f779a1b7d27b7ba8970 to your computer and use it in GitHub Desktop.
cf worker for giesela.blog
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(createResponse(event.request)) | |
}) | |
async function createResponse(req) { | |
let domain = new URL(req.url).hostname.toString(); | |
if (domain !== 'giesela.blog') { | |
let redirectHeaders = new Headers() | |
redirectHeaders.set('Location', 'https://giesela.blog') | |
return new Response('', { | |
status: 301, | |
headers: redirectHeaders | |
}) | |
} | |
let url = new URL(req.url).toString().replace("giesela.blog", "giesela.ghost.io") | |
const init = { | |
body: req.body, | |
headers: req.headers, | |
method: req.method | |
} | |
let response = await fetch(url, init) | |
let newHdrs = new Headers(response.headers) | |
if (newHdrs.has("Content-Type") && !newHdrs.get("Content-Type").includes("text/html") && !newHdrs.get("Content-Type").includes("text/xml")) { | |
return new Response(response.body, { | |
status: response.status, | |
statusText: response.statusText, | |
headers: newHdrs | |
}) | |
} | |
let text = await response.text() | |
let modified = text.replace('<script>"giesela.ghost.io"==window.location.hostname&&(window.location.href="https://giesela.blog"+window.location.pathname);</script>', '') | |
modified = modified.replace(/giesela.ghost.io/g, 'giesela.blog') | |
let urlPath = new URL(req.url).pathname | |
if (urlPath === '/ghost' || urlPath === '/ghost/') { | |
let redirectHeaders = new Headers() | |
redirectHeaders.set('location', 'https://giesela.ghost.io/ghost/') | |
return new Response(modified, { | |
status: 302, | |
headers: newHdrs | |
}) | |
} | |
let originPath = new URL(response.url).pathname | |
if (originPath !== urlPath) { | |
let redirectHeaders = new Headers() | |
redirectHeaders.set('Location', 'https://giesela.blog' + originPath) | |
return new Response('', { | |
status: 301, | |
headers: redirectHeaders | |
}) | |
} | |
return new Response(modified, { | |
status: response.status, | |
statusText: response.statusText, | |
headers: newHdrs | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment