Cloudflare Location Check


Recently I had a client come to me with a very interesting problem. They have multiple web servers running behind a Cloudflare load balancer and the majority of those requests flow through the load balancer and are directed properly. However, there were still a number of requests that would make it through straight to the origin IP’s. The majority of those requests were often attempts at common WordPress exploits or simply plugin scanning looking for vulnerable plugins. If those requests were properly going through Cloudflare they would be dealt with by the Cloudflare firewall but by using the IP address these bad actors were able to bypass that layer of security.

Thankfully Cloudflare has a way to check to see if the request actually passed through Cloudflare if the website has turned on the Cloudflare IP Geolocation. That service automatically adds the country code value passed along in the CF-IPCountry request header to the origin web server. If you want to know more about the Cloudflare IP Geolocation check out their support document.

The logic is pretty simple, if the request does not have the CF-IPCountry request header then the request did not pass through Cloudflare (and the Cloudflare Firewall) so redirect the request back to the fully qualified domain name.

/** * Cloudflare Location Check * * Checks for the Cloudflare location header. This is only there if the visitor has come through Cloudflare. * If the request does not have this it is direct access and should be redirected to the host name * */ function lgr_cflocation_check () { //the country header is added by Cloudflare. If it is not there then this is direct IP access and needs to be redirected. if( !$_SERVER["HTTP_CF_IPCOUNTRY"] ) { //send them to the full URL which should add it. header("Location: ".home_url().$_SERVER['REQUEST_URI']); die(); } } add_action( 'init', 'lgr_cflocation_check' );

If you are having problems with direct access to your website through the IP address this might help you.

Categories: classicpress wordpress