也许这是微不足道的,但我还没有找到任何有意义的东西,或者我不知道去哪里找……
(如何)可以在请求某个路径时立即发送curl /任何命令?
一些类似的东西,但这实际上是可行的:
location / {
curl --data 'v=1&t=pageview&tid=UA-XXXXXXXX-X&cid=123&dp=hit' https://google-analytics.com/collect
}
发布于 2019-01-08 17:07:59
下面是我最终是如何做到的--基于https://github.com/vorodevops/nginx-analytics-measurement-protocol/tree/master/lua,而不是curl,而是proxy_pass。代码假设是openresty或只安装了lua。不确定注释格式是否兼容(未测试),因此最好在使用前将其删除。
# pick your location
location /example {
# invite lua to the party
access_by_lua_block {
# set request parameters
local request = {
v = 1,
t = "pageview",
# don' forget to put your own property here
tid = "UA-XXXXXXX-Y",
# this is a "unique" user id based on a hash of ip and user agent, not too reliable but possibly best that one can reasonably do without cookies
cid = ngx.md5(ngx.var.remote_addr .. ngx.var.http_user_agent),
uip = ngx.var.remote_addr,
dp = ngx.var.request_uri,
dr = ngx.var.http_referer,
ua = ngx.var.http_user_agent,
# here you truncate the language string to make it compatible with the javascript format - you'll want either the first two characters like here (e.g. en) or the first five (e.g en_US) with ...1, 5
ul = string.sub(ngx.var.http_accept_language, 1, 2)
}
# use the location.capture thingy to send everything to a proxy
local res = ngx.location.capture( "/gamp", {
method = ngx.HTTP_POST,
body = ngx.encode_args(request)
})
}
}
# make a separate location block to proxy the request away
location = /gamp {
internal;
expires epoch;
access_log off;
proxy_pass_request_headers off;
proxy_pass_request_body on;
proxy_pass https://google-analytics.com/collect;
}
发布于 2019-01-01 17:38:26
(正如评论中指出的),ngx_http_lua_module
可以做到!
location / {
access_by_lua_block {
os.execute("/usr/bin/curl --data 'v=1&t=pageview&tid=UA-XXXXXXXX-X&cid=123&dp=hit' https://google-analytics.com/collect >/dev/null 2>/dev/null")
}
}
请注意,执行会暂停页面加载,直到curl完成。要在后台运行curl并立即继续页面加载,请在末尾添加一个空格和一个&
,如下所示
>/dev/null 2>/dev/null &")
发布于 2019-01-05 22:20:03
如果你所需要的只是向谷歌分析提交一个点击,那么它可以更容易地完成: Nginx可以动态修改页面HTML,在关闭的</body>
标签之前嵌入GA代码:
sub_filter_once on;
sub_filter '</body>' "<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');
</script></body>";
location / {
}
这个Nginx模块被称为sub
。
https://stackoverflow.com/questions/53975285
复制相似问题