在 前文 中,我已介绍过通过 Nginx proxy_pass 实现的方案。而本文所述方案,数据的生成和提交(via)均完全由 Openresty 实现,不再使用 Nginx proxy_pass 向 Google 发起 GET 请求,而使用 lua-resty-http 发起 POST 提交数据。
基本思路
通过 lua-resty-http 发起 POST 请求:
-- 指定你网站的 GA 数字 -- local tid = "UA-111111111-1" local tid = -- 生成统计数据 local post_body = "v=1&t=pageview&tid=" .. tid .. "&uip=" .. ngx.var.remote_addr .. "&cid=" .. ngx.var.cookie_cid .. "&dp=" .. cookie_uri .. "&dr=" .. http_referer .. "&z=" .. ngx.var.msec -- 发起 POST 请求 local http_new = http.new() http_new:request_uri("https://www.google-analytics.com/collect", { version = 1.1, method = "POST", headers = { ["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8", ["User-Agent"] = ngx.var.http_user_agent }, body = post_body, ssl_verify = false })
配置 Nginx
在上面已提出了基本思路,完整的 Nginx 实现应该是这样的框架:
location / { ... header_filter_by_lua_file /path/to/conf/headerfilter.lua; mirror /google_analytics; mirror_request_body on; } location /google_analytics { internal; resolver 8.8.8.8 ipv6=off; resolver_timeout 10s; access_by_lua_file /path/to/conf/access.lua; content_by_lua_file /path/to/conf/content.lua; }
其中, headerfilter.lua
和前文中的 access.lua 基本一致。本文所述方案和前文所述方案的区别,在于本文中所使用的 access.lua 和 content.lua。
以及需要注意的是,本文不再使用 post_action 而改用 mirror 指令(via)。
Lib 实现
本文仅提供最基本的思路介绍,完整的实现方案我已封装为 lib 并发布于 Github。
本站已使用本文所述方案,效果可参见本站 cookie。