chaihongjun.me

为nginx的访问日志添加访客地域信息

QQ截图20170609153609.jpg

一般的nginx访问日志仅仅包含访客IP,访客UA,访问时间,访客访问页面URL及状态码等信息,如想直观了解访客的大概区域是无法做到的,这里可以用nginx+geoip配合在nginx的日志输出访客的大致地理区域(国家-省份/州-城市),而无需再通过其他方法IP查询地域。

首先,nginx需要安装geoip模块--with-http_geoip_module,安装请参考《nginx搭配GeoIP数据屏蔽访问》,然后下面是具体的配置:

  1. 修改nginx.conf配置项,在http段

http{
  ...
geoip_country /usr/local/share/GeoIP/GeoIP.dat;
geoip_city /usr/local/share/GeoIP/GeoLiteCity.dat;
...
}

之后添加访问日志格式设定,因为前面引入了地理位置数据:

http {
    ...

        geoip_country /usr/local/share/GeoIP/GeoIP.dat;
        geoip_city /usr/local/share/GeoIP/GeoLiteCity.dat;
      
     #添加日志格式设定 
    log_format analytics '$remote_addr"[$time_local]"$request"$status"$body_bytes_sent"'
                            '$http_referer"$http_user_agent"$http_x_forwarded_for"'
                            '$request_time"$upstream_addr"$host"$request_body'
                            '$geoip_country_name $geoip_region_name $geoip_city';
                            
             ...
      }

2.然后因为每个虚拟主机都有

include fastcgi.conf;

所以可以直接在这个文件内添加变量,在fastcgi.conf 最后添加:

#append for GeoIP
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE $geoip_latitude;
fastcgi_param GEOIP_LONGITUDE $geoip_longitude;

3.修改虚拟主机的日志格式

#access_log /alidata1/www/logs/chaihongjun.me_nginx.log combined;
#将comnined改成analytics
access_log /alidata1/www/logs/chaihongjun.me_nginx.log analytics;

4.重新加载nginx配置文件

效果如下:

112.90.141.121"[09/Jun/2017:15:34:30 +0800]"GET / HTTP/1.1"301"178"-"DNSPod-Monitor/2.0"-"0.000"-"chaihongjun.me"-China Guangdong Guangzhou


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:chaihongjun»