Nginx和Apache配置日志格式记录Cookie

记录Cookie有什么用?

  有时候咱们须要经过web服务器的访问日志来统计UV(独立访客),并据此分析用户的行为。而UV是依据cookie数据得出的统计。UV相对于IP的好处是:IP是一个反映网络虚拟地址对象的概念,UV是一个反映实际使用者的概念,更加准确地对应一个实际的浏览者。使用UV做为统计量,能够更加准确的了解单位时间内实际上有多少个访问者来到了相应的页面。php

如何记录Cookie?

Nginx:

在nginx的配置文件中,能够经过$http_cookie来访问Cookie.html

想要记录Cookie,你须要修改nginx.conf配置文件。下面看一下具体的配置方法。nginx

找到以下代码,web

1 #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
2 #                  '$status $body_bytes_sent "$http_referer" '
3 #                  '"$http_user_agent" "$http_x_forwarded_for"';

若是你要记录整个Cookie,在下面添加一个新的log_format正则表达式

1 log_format  access_with_cookie  '$remote_addr - $remote_user [$time_local] "$request" '
2                                 '$status $body_bytes_sent "$http_referer" '
3                                 '"$http_user_agent" "$http_x_forwarded_for" "$http_cookie"';

而后在合适的位置上添加apache

access_log  /usr/share/nginx/logs/access_with_cookie.log  access_with_cookie;

 

若是你要记录Cookie的一部分,则你须要截取$http_cookie的内容。服务器

如今假设咱们在php中设置一个Cookie,cookie

  <?php
       setcookie('uuid' , '137C6BAE-DE1F-4F5F-51ED-5E1AA1B55A17' , time() + 3600*24);
  ?>

$http_cookie大概会是这样的网络

uuid=137C6BAE-DE1F-4F5F-51ED-5E1AA1B55A17ui

若是想仅仅记录  137C6BAE-DE1F-4F5F-51ED-5E1AA1B55A17。

则须要在nginx.conf的server段添加

1  if ($http_cookie ~* ".*uuid=(.*)(?:;|$)")
2  {
3      set $cookie_uuid $1;
4  }

并修改logformat,用$cookie_uuid代替$http_cookie

上面的配置涉及到了nginx的正则表达式。我对于正则表达式也不是很了解,这里仅说一下个人理解,不保证正确。

$1表明正则表达式中第一个括号里边的内容。

好了,在nginx日志里记录Cookie大概就是上面这个样子。

Apache

nginx配置网络上的文章比较多,但Apache得相对少一些。把个人方法说明一下,原理是同样的,只是语法有些差异。

Apache已经预置了获取Cookie某个字段的方法:%{VARNAME}C,因此配置起来会相对简单一点。

编辑httpd.conf,找到下面的内容。

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

在它之上加1行,

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"  \"%{uuid}C\"" combined_with_cookie

%{VARNAME}C表明cookie中VARNAME的值。仅支持version 0 cookies。关于Apache的LogFormat可参考这里,有详细的说明。

修改

CustomLog "logs/access_log" common

CustomLog "logs/access_log" combined_with_cookie

另外整个Cookie的值能够使用%{Cookie}i获取。 

 

以上仅是本身的经验总结,不保证其正确性,仅供参考。

相关文章
相关标签/搜索