TIL: Menggunakan Cloudflare Workers untuk Redirect

Hari ini saya perlu membuat redirect URL yang simpel untuk project pribadi. Instead of spinning up a full server, saya pakai Cloudflare Workers yang gratis dan sangat cepat.

Kenapa Cloudflare Workers?

  • Gratis — 100,000 requests/hari gratis
  • Edge location — Dekat dengan user, latency rendah
  • Mudah — Hanya beberapa baris JavaScript

Cara Buat

  1. Buka Cloudflare Dashboard
  2. Pilih domain → Workers & Pages
  3. Create Worker
  4. Paste kode berikut:
export default {
  async fetch(request) {
    const url = new URL(request.url);
    
    // Redirect rules
    const redirects = {
      '/old': 'https://yehartanto.my.id/new',
      '/blog': 'https://yehartanto.my.id/posts',
    };

    const destination = redirects[url.pathname];
    if (destination) {
      return Response.redirect(destination, 301);
    }

    return fetch(request);
  }
};
  1. Save and Deploy

Hasil

Redirect /old/new dengan status code 301 (Permanent Redirect).

Simpel dan efektif!


#TIL #Cloudflare #DevOps