1. Home
  2. Platform Administration
  3. Setting Up Reverse Proxy on CloudFlare

Setting Up Reverse Proxy on CloudFlare

Important: If you haven’t already, please read through the How to Setup Reverse Proxy for a PathFactory Instance before reading this article.

A reverse proxy, whether it’s a server, application, or cloud service, acts as a middleman, managing and optimizing the flow of information between visitors and the website domains they want to access. When using reverse proxy with PathFactory, visitors experience a seamless navigation flow and see PathFactory destination experiences as subfolder/subdirectory URLs within your primary domain folder structure vs. as a subdomain – i.e., companydomain.com/resourcehub vs. resourcehub.companydomain.com. Additionally, reverse proxy enhances security and helps distribute incoming requests across multiple servers to balance the load on busy websites.

Prerequisite: To establish a reverse proxy on CloudFlare, you must have an Enterprise subscription.

Follow these steps to implement the code snippet provided below:

  1. Copy the entire code sample below.
  2. Paste the code into a text editor.
  3. Replace specific placeholders within the code:
  • Replace <subdirectory> with your organization’s subdirectory name.
  • Replace <mycompany> with your organization’s name.
  1. Copy the modified code.
  2. Paste the modified code into a script or configuration file.
const htmlResponse = `

<!DOCTYPE html>

<html>

<head>

<title> Reverse Proxy test in progress </title>

</head>

<body > 

 <h1> Test example for cloudflare reverse proxy with PathFactory </h1>

 </body>

 </html>

`;

addEventListener('fetch',event => {

  event.respondWith(handleRequest(event.request))

})

async function handleRequest(request) {

const host = request.headers.get('host') ;

console.log("origin host ",host)

const url_original = new URL(request.url)

const pathname = url_original.pathname

console.log(" origin pathname",pathname)

const query_string = url_original.search;

   // if the path contains explore then send req to pathfactory 

  if (pathname.includes('/<subdirectory>')) { 

    const targetserver = 'https://<mycompany.pathfactory.com>' + pathname

    const url = new URL(targetserver) 

    const params = new URLSearchParams(query_string)

    params.forEach((value,key) => {

    url.searchParams.append(key,value)

    })

    const modifiedRequest = new Request(url.toString()); 

    modifiedRequest.headers.set('X-Forwarded-Host',host )

    modifiedRequest.headers.set('Cookie',request.headers.get('Cookie') || '')

    const response = await fetch(modifiedRequest)

    return response;

  }

  return new Response(htmlResponse, {

    headers: {'Content-type':'text/html'}

  })

}

Updated on March 26, 2024

Was this article helpful?

Need Support?
Can't find the answer you're looking for? Don't worry we're here to help!
CONTACT SUPPORT