Last active
October 10, 2018 15:59
-
-
Save mrkurt/fb5ba18ce5bba1bd3f4dc5f9f726b066 to your computer and use it in GitHub Desktop.
Kurt
This file contains hidden or 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
import proxy from "@fly/proxy" | |
import { forceSSL } from './lib/utilities' | |
const origin = proxy("https://viaglamour.com/") | |
/** | |
* Rewrite the path to /store/<hostname> | |
*/ | |
function rewriteRequest(req) { | |
const url = new URL(req.url) | |
let path = "/store/" + url.hostname.replace(/\.[a-z]+/, '') | |
path = path + url.pathname | |
const trailingSlash = path[path.length - 1] === '/' | |
path = path + (!trailingSlash && "/" || "") | |
const newURL = new URL(path, url) | |
newURL.search = url.search | |
console.log("rewriting path:", url.pathname, path, newURL.toString()) | |
return new Request(newURL.toString(), req) | |
} | |
/** | |
* Rewrites links in HTML from /store/hostname/ to / | |
*/ | |
async function rewriteResponseLinks(req, resp) { | |
const url = new URL(req.url) | |
resp.headers.set("custom-domain", url.hostname ) | |
// return resp | |
const contentType = resp.headers.get("content-type") || "" | |
if (!contentType.includes("html")) { | |
// skip non-html | |
return resp | |
} | |
const pathPrefix = "\/store\/" + url.hostname.replace(/\.[a-z]+/, '') + "\/" | |
const urlPattern = new RegExp(`https:\/\/viaglamour\.com${pathPrefix}`, 'g') | |
const pathPattern = new RegExp(pathPrefix, 'g') | |
let body = await resp.text() | |
console.log("replacing links:", urlPattern) | |
body = body.replace(urlPattern, "/") | |
console.log("replacing paths:", pathPattern) | |
body = body.replace(pathPattern, "/") | |
resp.headers.delete("content-length") | |
return new Response(body, resp) | |
} | |
/** | |
* Rewrites requests, proxies them through to origin, rewrites html | |
*/ | |
fly.http.respondWith(forceSSL(async function (req) { | |
req.headers.delete("accept-encoding") // so we can rewrite the body | |
const url = new URL(req.url) | |
req.headers.set("x-requested-domain", url.hostname) | |
const redirect = handleWWW(req) | |
if(redirect) return redirect; | |
const rewritten = rewriteRequest(req) | |
const resp = await origin(rewritten) | |
return rewriteResponseLinks(req, resp) | |
})) | |
function handleWWW(req){ | |
if(req.hostname.startsWith("www."){ | |
const url = req.url.replace(/www\./, '') | |
return Response.redirect(url, 301) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment