Cloudflare pages on main domain while routing sub-directories to CF load balancer

Hi all,

Got a unique question that I don’t really have a solid answer for.

We are moving our main domain (domain.com) to pages, but we need two subdirectories to route to our origin via CF load balancer (/example, /example2).

Is there any way to achieve this? I know workers can route to an origin, but I’m unsure if it can to a CF load balancer.

Something like this should do it. Make sure the hostname specified in resolveOverride is within the same zone. So, if the request is to app.example.com (zone: example.com), the load balancer hostname should be something like lb1.example.com. If the load balancer is external (AWS, GCP etc.), simply create a CNAME record on lb1.example.com pointing to the AWS/GCP load balancer hostname.

export default {
	async fetch(request) {
		const requestUrl = new URL(request.url)
		if (requestUrl.pathname.startsWith('/example1/')) {
			// Send request to load balancer #1
			return fetch(request, {
				cf: {
					resolveOverride: 'lb1.your-domain.example'
				}
			})
		} else if (requestUrl.pathname.startsWith('/example2/')) {
			// Send request to load balancer #2
			return fetch(request, {
				cf: {
					resolveOverride: 'lb2.your-domain.example'
				}
			})
		} else {
			// Send request to Cloudflare Pages
			return fetch(request)
		}
	}

If you are on the Enterprise plan, you can instead use Origin Rules to achieve this.

1 Like

The load balancer is at Cloudflare, not AWS / GCP which is attached to the primary domain.

That should still work for load balancers on Cloudflare. Just create the load balancer on an arbitrary subdomain and use that in resolveOverride.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.