-3

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?

Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64

1 Answers1

2

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;
  }
}
Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64
  • Please where do I put this code inside Laravel project – Syntax Byte Solutions Apr 20 '22 at 14:00
  • I do not know what your project looks like! You're going to need to share more info. – Alicia Sykes Apr 20 '22 at 14:02
  • Thank you. I don't really know what to share but my project is pure Laravel Framework – Syntax Byte Solutions Apr 20 '22 at 14:08
  • You need to put this code, where you want the redirects to happen... I can give you more detailed examples, if you update your question with more info. If my answer has helped you, then consider accepting it – Alicia Sykes Apr 20 '22 at 14:10
  • 1
    @SyntaxByteSolutions If this is a Laravel project, you would have a Route associated with each Country, like `Route::get('/{country}', ...);` This would then make more sense as a Middleware, where it detects your IP and redirects accordingly. Please review the documentation: https://laravel.com/docs/9.x/middleware – Tim Lewis Apr 20 '22 at 14:11