Skip to content

Instantly share code, notes, and snippets.

@sureshsaggar
Last active June 26, 2022 20:35
Show Gist options
  • Save sureshsaggar/4391407 to your computer and use it in GitHub Desktop.
Save sureshsaggar/4391407 to your computer and use it in GitHub Desktop.
Setup GeoIP with NginX & PHP
On my Ubuntu machine I located the GeoIP.dat file. If not available then download/intall the same.
root@localhost:~# locate GeoIP.dat
/usr/share/GeoIP/GeoIP.dat
Open Nginx configuration (/etc/nginx/nginx.conf) and specify <geoip_country> <path to GeoIP.dat>
line under the "http" block. Example block:
http {
# SS - meant to find country code from the client IP
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /etc/nginx/geoip/GeoLiteCity.dat;
....
I only required GEOIP_COUNTRY_CODE, but you can add many more like GEOIP_COUNTRY_NAME, GEOIP_REGION,
GEOIP_CITY, GEOIP_POSTAL_CODE, GEOIP_CITY_CONTINENT_CODE, GEOIP_LATITUDE, GEOIP_LONGITUDE etc.
depending on what all *.dat files you have specified inside http block. See http://wiki.nginx.org/HttpGeoipModule.
To make these variables available to PHP, add fastcgi_param directives inside /etc/nginx/fastcgi_params
i.e. add all params that you want the fastcgi to forward to PHP. I added for GEOIP_COUNTRY_CODE.
### SET GEOIP Variables ###
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
Now add "include /etc/nginx/fastcgi_params;" in your location block - one that serves your PHP code.
Example:
location ~ \.php$ {
if (!-e $request_filename) {
return 404;
}
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
include /etc/nginx/fastcgi_params;
}
Restart the php5-cgi process (use netstat -tap to find the PID). To test, I added the following location
block and let Nginx echo the user country code.
# Testing GeoIP
location ^~ /geoip/ {
add_header Content-Type application/json;
if ($geoip_country_code ~ "IN") {
echo '{"key":"india","country":"$geoip_country_code"}';
}
if ($geoip_country_code !~ "IN") {
echo '{"key":"global","country":"$geoip_country_code"}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment