Search code examples
cloudflarecloudflare-workers

Control cloudflare origin server using workers


I'm trying to use a cloudflare worker to dynamically set the origin based on the requesting IP (so we can serve a testing version of the website internally)

I have this

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

async function handleRequest(request) {
if (request.headers.get("cf-connecting-ip") == '185.X.X.X')
{
console.log('internal request change origin');
}

const response = await fetch(request)
console.log('Got response', response)
return response
}

I'm not sure what to set. The request object doesn't seem to have any suitable parameters to change.

Thanks


Solution

  • Normally, you should change the request's URL, like this:

    // Parse the URL.
    let url = new URL(request.url)
    
    // Change the hostname.
    url.hostname = "test-server.example.com"
    
    // Construct a new request with the new URL
    // and all other properties the same.
    request = new Request(url, request)
    

    Note that this will affect the Host header seen by the origin (it'll be test-server.example.com). Sometimes people want the Host header to remain the same. Cloudflare offers a non-standard extension to accomplish that:

    // Tell Cloudflare to connect to `test-server.example.com`
    // instead of the hostname specified in the URL.
    request = new Request(request,
        {cf: {resolveOverride: "test-server.example.com"}})
    

    Note that for this to be allowed, test-server.example.com must be a hostname within your domain. However, you can of course configure that host to be a CNAME.

    The resolveOverride feature is documented here: https://developers.cloudflare.com/workers/reference/apis/request/#the-cf-object

    (The docs claim it is an "Enterprise only" feature, but this seems to be an error in the docs. Anyone can use this feature. I've filed a ticket to fix that...)