Home Articles Cloudflare Workers Cloudflare Workers Reverse Proxy

Cloudflare Workers Reverse Proxy

Cloudflare Workers can be used in an easy way to proxy and route traffic. There are many different use-cases. In this example we'll deliver a documentation section from a separate installation, on a specific path on the public domain.

The simplest form reverse proxy worker

If you want to deliver the contents from, for example, mydocssite.com on the URL mypublicwebsite.com/docs/ – a simple Cloudflare workers reverse proxy might do the trick.

  • Requires the origin to be configured with the public URL, in this example https://mypublicwebsite.com/docs
  • Works for GET requests (meaning, you can for example not log in or submit forms)
const DOMAIN = 'mypublicwebsite.com';    //
const PROXYPATH = 'docs';                // path to be proxied
const ORIGIN = 'mydocssite.com';         // where to fetch content from

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/' + PROXYPATH + '/') || url.pathname === '/' + PROXYPATH) {
    handleRequest(event, url);
  } else {
    event.respondWith(fetch(event.request));
  }
})

async function handleRequest(event, url) {
  // Change URL from public URL to use the origin URL
  var originUrl = url.toString().replace(
      'https://' + DOMAIN + '/' + PROXYPATH, 
      'https://' + ORIGIN
    );
    event.passThroughOnException();
    event.respondWith(fetch(originUrl));
}

After creating this worker in the Cloudflare workers dashboard for your public domain, in this example mypublicwebsite.com, you need to assign a route. That will tell Cloudflare to trigger your worker, when requests are sent to /docs/*.

If your origin is running a WordPress installation, you should configure it to use mypublicwebsite.com/docs as the site URL. With this correctly set up, a request to mypublicwebsite.com/docs/article-1/ will be fetched from mydocssite.com/article-1/.

Conditional routing

Conditional routing is another way to use a reverse proxy. It is a lot easier and more flexible to implement logic on the network edge in a JavaScript worker, than to configure it in the configuration files of the server, or even within your PHP applications.

Did this help you?