Block Traffic via GeoIP on Cloudways

YouTube video

Written By

Jonathan Jernigan

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'll share with you the tl;dr of new blog posts and videos, exciting announcements, and other valuable information from around the WordPress ecosphere. You'll never get more than one email per week from me.

"*" indicates required fields

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