Skip to content

Instantly share code, notes, and snippets.

@keiraarts
Last active August 24, 2018 20:49
Show Gist options
  • Save keiraarts/64de2ecb131c35102ab37f62887029af to your computer and use it in GitHub Desktop.
Save keiraarts/64de2ecb131c35102ab37f62887029af to your computer and use it in GitHub Desktop.
Broken HTML rewrites
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 newURL = new URL(path, url)
console.log("rewriting path:", url.pathname, path)
return new Request(newURL.toString(), req)
}
/**
* Rewrites links in HTML from /store/hostname/ to /
*/
async function rewriteResponseLinks(req, resp) {
const contentType = resp.headers.get("content-type") || ""
if (!contentType.includes("html")) {
// skip non-html
return resp
}
const url = new URL(req.url)
const pathPrefix = "\/hiring\/" + 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 rewritten = rewriteRequest(req)
const resp = await origin(rewritten)
return rewriteResponseLinks(req, resp)
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment