Sample CloudFlare worker that does redirects and rewrites.
Last active
July 3, 2020 14:33
-
-
Save rstacruz/aae33b3786126dc940d623cb36900e21 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 => { | |
let response = handleRequest(event.request) | |
event.respondWith(response) | |
}) | |
/** | |
* Fetch and log a given request object. | |
* Fill up this function with if + return fetch rules. | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
const url = new URL(request.url) | |
// Redirect www.devhints.io => devhints.io | |
if (url.hostname === 'www.devhints.io') { | |
url.protocol = 'https:' | |
url.hostname = 'devhints.io' | |
return Response.redirect(url.toString(), 301) | |
} | |
// Redirect http to https | |
if (url.protocol === 'http:') { | |
url.protocol = 'https:' | |
return Response.redirect(url.toString(), 301) | |
} | |
// Redirect til.ricostacruz.com => ricostacruz.com/til | |
if (url.host === 'til.ricostacruz.com') { | |
url.protocol = 'https:' | |
url.host = 'ricostacruz.com' | |
url.pathname = '/til' + url.pathname | |
return Response.redirect(url.toString(), 301) | |
} | |
// Rewrite ricostacruz.com/til => rstacruz-tilnext.netlify.app/til | |
if (url.pathname.match(/^\/til\/.*$/)) { | |
url.protocol = 'https:' | |
url.host = 'rstacruz-tilnext.netlify.app' | |
// Optional: set some cloudflare settings | |
request.cf = { cacheTtl: 86400, cacheEverything: true } | |
return fetch(url.toString(), request) | |
} | |
// Fallback | |
return fetch(request.url, request) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment