Intro
Nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server. In this article, we will demonstrate how to add a country code to your Nginx log via the IP2Location Nginx Module for the Debian Linux environment.
Pre-requisites
Please make sure you have downloaded and decompressed the latest Nginx sources from https://nginx.org/en/download.html
You also need to download the IP2Location Nginx module from https://github.com/ip2location/ip2location-nginx
The last pre-requisite is the IP2Location BIN database file which you can get from:
https://www.ip2location.com/database/ip2location (commercial)
or
https://lite.ip2location.com/ip2location-lite (free LITE version, less accurate)
See the comparison of IP2Location commercial and LITE database.
Download and decompress the BIN file into a folder called ip2location.
Installation
First of all, we need to get the IP2Location C library via the below link:
https://github.com/chrislim2888/IP2Location-C-Library/archive/master.zip
Download the above and decompress in a folder called ip2location.
Navigate to the IP2Location-C-Library-master sub-folder.
cd IP2Location-C-Library-master
Now, compile the IP2Location C library by running the below commands.
sudo autoreconf -i -v --force sudo ./configure sudo make sudo make install
Next, get the IP2Location Nginx module via the below link:
https://github.com/ip2location/ip2location-nginx/archive/master.zip
Download the above and decompress into the ip2location folder from above.
Now, go to Nginx source codes folder.
cd nginx-x.y.z
Compile Nginx from source to include IP2Location Nginx module.
./configure --add-module=/absolute/path/to/ip2location-nginx-master make make install
Configuration
Add following lines into the /etc/nginx/nginx.conf (Or /usr/local/nginx/conf/nginx.conf) file. Modify the ip2location_database parameter for your own folder and BIN filename.
http { ... ip2location_database /absolute/path/to/ip2location/bin/database.BIN; }
Also, add a custom format for the log file:
log_format custom_format '$ip2location_country_short $remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"'
Update existing log to use this custom format:
access_log /var/log/nginx/access.log custom_format;
Then save the file. The above format modification adds another field to the front of the log entry to show the country code for the geolocation information of that IP address.
Restart Nginx for the above settings to take effect
Run the following command to restart.
sudo systemctl restart nginx
Open your browser and navigate to your webpage
Your log should now have an entry like the below:
MY 175.138.99.179 - - [18/Nov/2021:00:00:02 +0000] "GET / HTTP/1.1" 200 3872 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0"
In this case, the country code is MY for Malaysia.