Home  >  Article  >  Backend Development  >  How to Automatically Redirect Domain Visitors Based on Their IP Country?

How to Automatically Redirect Domain Visitors Based on Their IP Country?

Barbara Streisand
Barbara StreisandOriginal
2024-10-17 14:22:29443browse

How to Automatically Redirect Domain Visitors Based on Their IP Country?

Redirecting Domains Based on User IP Country

Problem:

You wish to automatically redirect users to specific subdomains based on their country's IP address. For instance, if a user from India visits abcd.com, they should be redirected to ind.abcd.com.

Solution:

To achieve country-specific redirection, you can utilize the GeoPlugin library. Follow these steps to implement it:

  1. Download GeoPlugin Class:
    Obtain the geoPlugin.class.php file from http://www.geoplugin.com/_media/webservices/geoplugin.class.phps. This library provides information about user's IP country location.
  2. Create an Index File:
    In your root folder, create a file named index.php with the following code:
<code class="php"><?php
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
// Country code variable
$var_country_code = $geoplugin->countryCode;

// Set redirect based on country code:
switch ($var_country_code) {
    case "AL":
        header('Location: http://sq.wikipedia.org/');
        break;
    case "NL":
        header('Location: http://nl.wikipedia.org/');
        break;
    default:
        header('Location: http://en.wikipedia.org/');
}
?></code>
  1. Configure Country Codes:
    Within the switch statement, add country codes along with their corresponding subdomains. You can find a list of country codes at http://www.geoplugin.com/iso3166.

This script will detect the user's IP address and automatically redirect them to the appropriate subdomain based on their country.

The above is the detailed content of How to Automatically Redirect Domain Visitors Based on Their IP Country?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn