Block Traffic via GeoIP on Cloudways

YouTube video

Written By

Jonathan Jernigan

Found at Permaslug and APEX Web Solutions

I have a client with a private portal who needed to block all traffic from non-USA IP addresses for spam purposes.

The site is hosted on Cloudways which offers a GeoIP feature built in, but turning it on does nothing by itself.

After digging through Cloudways documentation for setting up GeoIP and inputting some queries into WPCodey, I finally got a working code snippet.

Here is the code that worked for me. You can change the ‘Access denied’ message to anything you want. I chose to keep it vague.

Simple add this in as a code snippet via WPCodey* or functions.php and viola!

To test it was working, I used this tool: https://geotargetly.com/geo-browse

$FORWARDED_COUNTRY = getenv('HTTP_X_FORWARDED_COUNTRY');

if ($FORWARDED_COUNTRY !== 'United States') {
    // Block traffic
    wp_die('Access denied.');
}

*Affiliate link

Cloudways documentation link: https://support.cloudways.com/en/articles/5126366-how-to-use-geoip-with-your-application#h_158df011dc

Signup for the most inconsistent newsletter this side of the Mississippi

Delivered on a regular-as-I-can basis, I summarize the goings on here on Permaslug, share announcements, and other pertinent information. I hate garbage emails as much as you and promise not to contribute anymore to it.

  • This field is for validation purposes and should be left unchanged.