Hi
Can you white list a select few ips address and redirect everyone else for a whole domain? Is that possible with Cloudflare?
Thanks
Hi
Can you white list a select few ips address and redirect everyone else for a whole domain? Is that possible with Cloudflare?
Thanks
Greetings,
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 https://www.mydomain.com*
, 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 ):
// Redirect visitors to the URL
const redirectURL = "https://www.google.com/"
// 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 != '1.2.3.4' || myIP != '123.113.112.111' || myIP != '123.234.243.221') {
return Response.redirect(redirectURL, redirectHttpCode);
}else{
return new Response(url);
}
// Console debug
console.error(
"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 => {
event.respondWith(handleRequest(event.request));
});
Other solution would be using a Transform Rule followed by a Page Rule as described at the post of my colleague @michael from below:
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
const myIP = '123.113.112.111';
if(myIP != '1.2.3.4' || myIP != '123.113.112.111' || myIP != '123.234.243.221') {
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 !==
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.