Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active July 3, 2020 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/aae33b3786126dc940d623cb36900e21 to your computer and use it in GitHub Desktop.
Save rstacruz/aae33b3786126dc940d623cb36900e21 to your computer and use it in GitHub Desktop.

CloudFlare worker example

Sample CloudFlare worker that does redirects and rewrites.

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