How to redirect users to a directory based on Country in Laravel

1k Views Asked by At

I would like a user from different country to be redirected to a set directory in Laravel.

I have tried this URL redirecting base on information seen here, using:

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^DE$
RewriteRule ^(.*)$ http://example.com/germany [L]

Now it not working. Please how can I work it out?

1

There are 1 best solutions below

5
Alicia Sykes On

Step #1 - Get IP Address

Step one is easy enough

$_SERVER['REMOTE_ADDR']

Actually, this may not be the most accurate method. But this is covered in more detail in this thread

Step #2 - Get Region from IP

The only way to associate an IP with a region, is to use a third-party service. For example, ipinfo.io.

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->region; // E.g. england.

Step #3 - Redirect Page

Finally, you can then redirect the user using the above result.

switch ($region) {
  case 'england':
    header("Location: https://somewhere/england",TRUE,301);
    exit;
    break;
  case 'spain':
    header("Location: https://somewhere/spain",TRUE,301);
    exit;
    break;
  case 'germany':
    header("Location: https://somewhere/germany",TRUE,301);
    exit;                 
    break;
  default:
    header("Location: https://somewhere/england",TRUE,301);
    exit;
    break;
  }
}