Search code examples
nginxluahttp2openrestymeasurement-protocol

Sending http requests with Openresty to Google Analytics


I have been using openresty/nginx+lua to send server-side hits to Google Analytics Measurement Protocol. However, the function I'm using (ngx.location.capture) is incompatible with HTTP/2 and a "won't fix" issue. Apparently, the way to go is to use the 'resty.http' module. I must be doing something wrong migrating, because it no longer sends the hits along.

Here's the code that works:

location /example {
    resolver 8.8.8.8 ipv6=off;
    access_by_lua_block  {
        local request = {
        v = 1,
        t = "pageview",
        tid = "UA-XXXXXXX-Y",
        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,
        ul = ngx.var.http_accept_language
        }

        local res = ngx.location.capture(  "/gamp",  {
        method = ngx.HTTP_POST,
        body = ngx.encode_args(request)
        })
    }
}

    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;
    }

Here's how I tried and failed:

location /example {
        access_by_lua_block  {
                    local request = {
                    v = 1,
                    t = "pageview",
                    tid = "UA-XXXXXXX-Y",
                    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,
                    ul = ngx.var.http_accept_language
                    }

            local http = require "resty.http"
            local httpc = http.new()
            local res, err = httpc:request_uri("https://google-analytics.com/collect", {
            method = "POST",
            body = ngx.encode_args(request)
            })
    }
}

Solution

  • You need to add two more directives: resolver and lua_ssl_trusted_certificate.

    For example,

    server {
      ...
      resolver 8.8.8.8 ipv6=off;
      lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
      # optional
      # lua_ssl_verify_depth 5;
      ...
    }