To send requests based on geolocation to different pages in Nginx, you can use the Nginx GeoIP
module along with conditional statements in your Nginx configuration. Follow this recipe to get this done:
Install the GeoIP module
- - Check if the
GeoIP
module is already installed by running the commandnginx -V
and looking for--with-http_geoip_module.
If it's not present, you need to recompile Nginx with theGeoIP
module. - - Download the
GeoIP
library from MaxMind or install it via your package manager (e.g.,apt-get, yum, or brew
). Notice: MaxMind Geo DB is not free. - - Install the GeoIP library using the appropriate commands for your operating system.
Configure the GeoIP database
- - Obtain a
GeoIP
database from MaxMind (e.g., GeoLite2). - - Extract the database file (e.g.,
GeoLite2-Country.mmdb
) and place it in a suitable location on your server.
Configure Nginx
- - Open your Nginx configuration file (typically located at
/etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf
). - - Add the following lines inside the
http
block to load theGeoIP
module and define the path to theGeoIP
database
http {
# ...
geoip2 /path/to/GeoLite2-Country.mmdb {
auto_reload 60m;
$geoip2_metadata_country_build metadata build_epoch;
}
# ...
}
Define conditional statements
Within the server block of your Nginx configuration, use the geo
directive to define conditional statements based on geolocation. You can specify different pages or redirect to different URLs based on the user's location
server {
# ...
if ($geoip2_data_country_code = "US") {
return 301 https://www.example.com/us;
}
if ($geoip2_data_country_code = "GB") {
return 301 https://www.example.com/uk;
}
# Default location if no specific condition matches
return 301 https://www.example.com/default;
# ...
}
In the above example, if the user's country code is "US"
, they will be redirected to https://www.example.com/us
. If the country code is "GB"
, they will be redirected to https://www.example.com/uk
. For all other countries, they will be redirected to https://www.example.com/default
.
Passing the Geo Location as a parameter to be processed in PHP
To pass the country code as a parameter in the URL, you can modify the Nginx configuration to include the country code as a query parameter when redirecting the request.
server {
# ...
if ($geoip2_data_country_code = "US") {
return 301 https://www.example.com/endpoint.php?country=us;
}
if ($geoip2_data_country_code = "GB") {
return 301 https://www.example.com/endpoint.php?country=uk;
}
# Default location if no specific condition matches
return 301 https://www.example.com/endpoint.php?country=default;
# ...
}
By including the country code as a query parameter in the URL, you can access it in your web application or server-side script by parsing the request URL and extracting the value of the country parameter.