Nginx添加访客地理位置到日志(GeoIP模块)

之前项目里用Nginx吐出access日志,然后用awstats来统计分析,结果对于访客地理位置比较头痛,于是自己写了几个程序查找(纯真库和GeoIP查找的方法不一样),今天看Nginx源码时候发现了可以利用--with-http_geoip_module这个模块,然后指定变量到日志。具体会有瓶颈,下面看怎么实现。

GeoIP库安装


wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

mkdir /var/GeoIP
mv GeoIP.dat.gz /var/GeoIP/
gunzip /var/GeoIP/GeoIP.dat.gz
mv GeoLiteCity.dat.gz /var/GeoIP/
gunzip /var/GeoIP/GeoLiteCity.dat.gz

安装Nginx


wget http://tengine.taobao.org/download/tengine-1.4.6.tar.gz #不采用tengine也行
tar -zxvf tengine-1.4.6.tar.gz
cd tengine-1.4.6
./configure --with-http_geoip_module
make
make install

配置Nginx


http{

    ## Log Format设置日志格式,结尾添加了三个字段
    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" '   '"$http_user_agent" "$http_x_forwarded_for" ' '$geoip_country_name $geoip_region $geoip_city';
     ....
     server {
                listen  80 default;
                server_name  _;

                access_log /home/logs/localhost_access.log access;
                root /var/www/html;
                location / {
                        index index.html;
                }
        }
}

测试


访问 http://ip/
查看日志

#tail -f /home/logs/localhost_access.log
118.182.79.52 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 15 Lanzhou
59.44.96.101 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 19 Shenyang
223.220.164.78 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 06 Xining
125.75.235.74 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 15 Pingliang
220.191.225.5 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 02 Linhai
111.85.193.166 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 18 Guiyang
125.75.213.24 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 15 Lanzhou
114.139.231.82 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 19 Guizhou
180.95.139.105 - - [29/Aug/2013:13:39:50 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "-" China 15 Lanzhou

更多配置可以参考 http://nginx.org/en/docs/http/ngx_http_geoip_module.html#example

总结


我查看了下Nginx加了GeoIP后内存的消耗,因为之前Nginx的GeoIP模块里读取了GeoIP的国家库和城市库,这两个文件大概占了20M内存,所以Nginx比没加GeoIP的时候刚好多耗了20M内存,20M对Nginx已经是很奢侈的事情。Nginx对于内存管理做到极致,所以低内存消耗是出了名的。有时间分析下Nginx的GeoIP源码。

标签:Nginx

评论已关闭