可搜索,可注册,可登录,致敬逗比大佬!尽在救援版逗比根据地 dbgjd.com
投稿文章 | 广告合作 | Telegram 群组 / 公告频道 / 使用教程

Google_Analytics 异步化方案 via Openresty(第二章)

News mlone11978 576℃ 0评论

前文 中,我已介绍过通过 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。

转载请注明:逗比根据地 » Google_Analytics 异步化方案 via Openresty(第二章)

喜欢 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址