Can you white list a select few ips address and redirect everyone else for a whole domain?


Can you white list a select few ips address and redirect everyone else for a whole domain? Is that possible with Cloudflare?



Thank you for asking.

I believe yes, this could be done with Cloudflare Workers using the cf-connecting-ip field to check if the IP from the HTTP request is in the array/list, therefore pass it, otherwise using a redirect method move that visitor to some other URL location.

If I setup a Worker on a URI like*, I am not sure if below code for a Worker would work, I’ve written in without double-checking, maybe @Walshy could take a look at this (I might learn something new again :slight_smile: ):

// Redirect visitors to the URL
const redirectURL = ""

// HTTP 301 Redirect 
const redirectHttpCode = 301

// Request
async function handleRequest(request) {
  // Get visitor IP
  const myIP = request.headers.get('CF-Connecting-IP');

  const url = new URL(request.url)
  const { pathname } = url
  // Add my IPs here - would it work like that? Rather using array, etc.
  if (myIP != '' || myIP != '' || myIP != '') {
    return Response.redirect(redirectURL, redirectHttpCode);
    return new Response(url);

  // Console debug
    "Getting Client's IP address is not supported in playground. Must test on a live worker."

  // Execute
  return fetch(request);

// Fetch API Listener
addEventListener('fetch', event => {

Other solution would be using a Transform Rule followed by a Page Rule as described at the post of my colleague @michael from below:

1 Like

Looks pretty good!

Just a few small things, your if is doing ors so if even if it was one of those IPs, it would still fail on the other ors. If only one of those is true it’d redirect. This should be using ands instead :slight_smile:

const myIP = '';

if(myIP != '' || myIP != '' || myIP != '') {
    console.log('oh noes');

// prints: "oh noes"

Small nitpick too but != will not be strict on types. While it won’t matter here, just good practice to do !== :slight_smile:

Also, another small thing but you’re returning a new response of that URL, it’d just return that URL only haha. I think you meant to do return fetch(url) there (or not have the else, would work either way)


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