Implement HTTP redirect using cloudflare workers
5/5/2021, 4:12:19 AM
Sometimes we will need HTTP redirect eg. when using a new domain.
Here are the simplest solution: using cloudflare workers!

The principle: worker loads redirect rules from KV, then uses them to do redirects.

All you need is to create a new worker, copy-and-paste the code below, then bind a KV namespace to KV for this worker.

To add / modify redirect rules, use the KV panel in the Cloudflare dashboard.

Example redirect rules:

Key Value Description
^https?://(?:www.)?zzisu.dev(.*) !https://zisu.dev$1 Full site 301 redirect
^https?://www.swarm-p.com https://swarm-p.com Strip the www prefix

Worker code:

addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
    const res = await KV.list()
    for (const { name: key } of res.keys) {
        const matcher = new RegExp(key)
        if (matcher.test(request.url)) {
            /** @type string */
            let rule = await KV.get(key)
            let code = 302 // Found
            if (rule.startsWith('!')) {
                code = 301 // Moved Permanently
                rule = rule.substring(1)
            }
            const dist = request.url.replace(matcher, rule)
            return Response.redirect(dist, code)
        }
    }
    return Response.redirect('https://zisu.dev/')
}