LoginSignup
44
42

More than 5 years have passed since last update.

Nginxからトラッキング用のCookieを設定する

Last updated at Posted at 2014-02-05

やりたいこと

  • アクセスログからユニークユーザを特定したい。
    • proxyを通してアクセスをさばいているので、複数ユーザ/クライアントのログが丸められてしまっている。
  • Cookieベースでユーザを特定できるといいな。
  • 専用ツールの利用は無し(あとから考えよう)。
  • Apacheではなく、Nginxを使いたい。
    • かつ、Apacheのmod_usertrackのようなことをしたい。

ログからのトラッキング以外に、現在はPiwikというOSSのツールも使っています。こちらもとても面白いものなので、いつか簡単にご紹介します!

Nginxのモジュール対応表

Nginxのモジュール対応表を見てみます。
mod_usertrackに対応するのは、ngx_http_userid_module だそうです。

下記は、nginxの設定例。default.confなどに記載します。

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # トラッキングIDをログの末尾にくっつける
    log_format app_main  '$remote_addr - $proxy_add_x_forwarded_for - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for" "$uid_got"';

    access_log /var/log/nginx/nginx-access.log  app_main;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html/;
            index  index.html index.htm;
        }

        # トラッキングIDの設定
        userid          on;
        userid_name     app_uid;
        userid_domain   wp1.localhost;
        userid_path     /;
        userid_expires  365d;
    }
}

設定内容:

  • Cookie名を app_uid にする。
  • xxx.app.com に対して適用させる。
  • パスは/ (アプリケーションの特性にあわせて、/xxx のほうが良い場合もある) 。
  • 期限は365日。

Cookieの確認

上記の設定で実際にためしてみます。

  • NginxはVirtualBox / Vagrantで立ち上げたCentOS(ゲストOS)中で起動。
  • ホストOS側の /etc/hosts にwp1.localとしてゲストOSのIPを設定。(Vbox Privateネットワークで、192.168.33のネットワークになっています)
  • ホストOS側のFireFoxでアクセス。

wp-cookie.png

ログに出力させてみる

ログには、$uid_got で書き出すことができます。
下記は app_main という名前でカスタマイズしたログフォーマットの例です。
プロキシ経由でのアクセスが中心なので、以下のように proxy_add ... を指定しています

$remote_addr - $proxy_add_x_forwarded_for
log_format  app_main  '$remote_addr - $proxy_add_x_forwarded_for - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for" "$uid_got"';

下記は、実際のログの出力です。

192.168.33.1 - 192.168.33.1 - - [05/Feb/2014:06:01:01 +0900] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0" "-" "app_uid=0B21A8C0D851F1523E33BDBF02040303"

以上、こんな感じです。

44
42
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
42