Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geoip redirect countries to 403

I am having problem with blocking countries with geoip. When I use my hosting account utility to block countries, it creates the below script in a .htaccess. The problem is it does not seem to be working (added US but was not blocked).

GeoIPEnable on
RewriteEngine on
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^AU$   [OR]
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$   [OR]
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CN$   
   RewriteRule ^.*$ - [F] 

So, I added [OR] to the last country in the list but now it blocks everything including countries not in the list. Here I tried deleting US but still received 403 message.

GeoIPEnable on
RewriteEngine on
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^AU$   [OR]
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$   [OR]
   RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CN$   [OR]
   RewriteRule ^.*$ - [F]
like image 495
E G Avatar asked Nov 30 '25 08:11

E G


1 Answers

I did it without using .htaccess. I just placed the following snippet of code in header file. This might helpful for you:

<?php 
include("includes/lcs/geoip.inc"); //Also load this file for its functions.
$serverIP=$_SERVER['REMOTE_ADDR']; //Get the IP address.
//echo $serverIP;
$gi = geoip_open("includes/lcs/GeoIP.dat",GEOIP_STANDARD); //Get the 2 letter country designation for the IP address.
$restricted_countries = array("US"); // list of restricted countries like array("NP", "US"); 
$country = geoip_country_code_by_addr($gi, $serverIP);


$restricted_pages = array("country_login","country_contact","country_password_forgotten","account"); 


if( (in_array($country,$restricted_countries)) and (!in_array($_GET['main_page'],$restricted_pages) ) )
{   
    header("location: https://www.yoursite.com/country_contact.html");

}
?>

This simply redirects to the country_contact.html for restricted country.

like image 99
Vijaya Pandey Avatar answered Dec 02 '25 02:12

Vijaya Pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!