Cloudflare Docs
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

Redirect

Redirect requests from one URL to another or from one set of URLs to another set.

Redirect all requests to one URL

const destinationURL = 'https://example.com';
const statusCode = 301;

async function handleRequest(request) {
  return Response.redirect(destinationURL, statusCode);
}

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

Redirect requests from one domain to another

const base = 'https://example.com';
const statusCode = 301;

async function handleRequest(request) {
  const url = new URL(request.url);
  const { pathname, search } = url;

  const destinationURL = base + pathname + search;

  return Response.redirect(destinationURL, statusCode);
}

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