Skip to content

Instantly share code, notes, and snippets.

@auniverseaway
Created November 18, 2022 23:51
Show Gist options
  • Save auniverseaway/c47ad73dbbf493e3e3da9b8dd86443cb to your computer and use it in GitHub Desktop.
Save auniverseaway/c47ad73dbbf493e3e3da9b8dd86443cb to your computer and use it in GitHub Desktop.
/*
* A Cloudflare Worker to accept `.html` requests
* and forward to Franklin.
*
* This is helpful for any site that wishes to continue
* using `.html` for legacy reasons.
*
*/
const removeHtml = (path) => {
const pathSplit = path.split('/');
const page = pathSplit.pop();
const pageSplit = page.split('.');
const pageExt = pageSplit.pop();
if (pageExt !== 'html') return path;
const pageName = pageSplit.pop();
if (pageName === 'plain' && pageSplit.length > 0) return path;
const newPath = pathSplit.join('/');
if (pageName === 'index') return newPath;
return `${newPath}/${pageName}`;
};
const handleRequest = async (request, env, ctx) => {
const url = new URL(request.url);
url.hostname = env.ORIGIN_HOSTNAME;
url.pathname = removeHtml(url.pathname);
const href = `${url.origin}${url.pathname}${url.search}${url.hash}`;
const req = new Request(href, request);
req.headers.set('x-forwarded-host', req.headers.get('host'));
req.headers.set('x-byo-cdn-type', 'cloudflare');
req.headers.set('x-push-invalidation', 'enabled');
let resp = await fetch(req, {
cf: {
cacheEverything: true,
},
});
resp = new Response(resp.body, resp);
resp.headers.delete('age');
resp.headers.delete('x-robots-tag');
return resp;
};
export default {
fetch: handleRequest,
};
@tripodsan
Copy link

in https://gist.github.com/auniverseaway/c47ad73dbbf493e3e3da9b8dd86443cb#file-franklin-html-worker-js-L27-L30 why do you recompose the href manually and not just use the URL object? eg:

 url.hostname = env.ORIGIN_HOSTNAME;
 url.pathname = removeHtml(url.pathname);
 const req = new Request(url.href, request);

@rofe
Copy link

rofe commented Nov 19, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment