Skip to content

Nginx 反向代理 Google Analytics

反向代理 Google Analytics

批量修改 ga.yourdomain.com 为你的域名

nginx
server {
    listen 80;
    server_name ga.yourdomain.com;
    return 301 https://ga.yourdomain.com$request_uri;
}

server {
    listen 443   ssl http2;
    server_name  ga.yourdomain.com;

    ssl_certificate /ssl/yourdomain.com.cer;
    ssl_certificate_key /ssl/yourdomain.com.key;
    ssl_trusted_certificate /ssl/yourdomain.com.cer;

    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_ecdh_curve secp384r1;
    ssl_session_timeout  10m;
    ssl_session_cache builtin:1000 shared:SSL:10m;
    ssl_session_tickets off;
    resolver 8.8.8.8 8.8.4.4 valid=60s ipv6=off;
    resolver_timeout 5s;
    add_header Strict-Transport-Security "max-age=63072000" always;

    location /gtm.js {
        sub_filter 'www.googletagmanager.com' $server_name;
        sub_filter_types *;
        sub_filter_once off;

        proxy_set_header Accept-Encoding '';

        proxy_pass https://www.googletagmanager.com;

        proxy_redirect off;
        expires 1h;
    }

    location /gtag/js {
        sub_filter 'analytics.google.com' $server_name;
        sub_filter 'stats.g.doubleclick.net' $server_name;
        sub_filter 'www.googletagmanager.com' $server_name;
        sub_filter 'www.google-analytics.com' $server_name;
        sub_filter '"+a+".google-analytics.com' $server_name;
        sub_filter 'www.merchant-center-analytics.goog' $server_name;
        sub_filter_types *;
        sub_filter_once off;

        proxy_set_header Accept-Encoding '';

        proxy_pass https://www.googletagmanager.com;

        expires 1h;
    }

    location /g/collect {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass https://analytics.google.com$uri$is_args$args&_uip=$remote_addr;

        proxy_redirect off;
        expires epoch;
    }


    access_log /var/log/nginx/ga.yourdomain.com.access.log main;
    error_log  /var/log/nginx/ga.yourdomain.com.error.log warn;
}