nginx 给网页注入 script 内容

原创
2022/08/11 12:30
阅读数 776

很多内部系统,需要统一加上 埋点、客服入口、水印等,不想改代码的情况下,可以在 nginx 转发时,强制注入 script

server {
    listen 80;

    server_name ~^(cms|crm|oms|ehr|msg)-(\w+)\.wzw\.com$;
    set $project $1;
    set $envx $2;

    location /favicon.ico {
        proxy_set_header Host wzw-cdn.oss-cn-beijing-internal.aliyuncs.com;
        proxy_pass http://wzw-cdn.oss-cn-beijing-internal.aliyuncs.com;
    }

    location /api/ {
        add_header Cache-Control "no-cache, no-store";
        proxy_pass  http://172.16.220.179;
        proxy_set_header   Cookie           $http_cookie;
        proxy_set_header   Host             api-service-$envx.wzw.com;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

    if ($project = "msg") {
        set $project "msg/msg-v2";
    }


    if ($envx = "") {
        set $envx "daily";
    }

    location / {
        # 注入 js 统计脚本
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Accept-Encoding '';
        gzip off;
        sub_filter '</body>' '<script from="ng" src="//static.wzw.com/biz.js"></script></body>';
        sub_filter_types *;
        sub_filter_once off;

        add_header Cache-Control "no-cache, no-store";
        rewrite .* /$project/index.$envx.html break;
        proxy_set_header Host wzw-cdn.oss-cn-beijing-internal.aliyuncs.com;
        proxy_pass http://wzw-cdn.oss-cn-beijing-internal.aliyuncs.com;
    }
}

有两个坑:

  • Chrome 等默认启用 GZIP压缩,这时候会发现 Chrome 没有注入,curl 命令行请求的注入了
  • 类型过滤
    • sub_filter_types:*; 需要替换的类型,text/html text/plain application/javascript等,空格分隔
    • sub_filter_once: on/off; 是否只替换一次
    • sub_filter: xxx1  xxx2; 前面的参数为原始内容,后面为替换后的内容,只能配置一个sub_filter?

参考:

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部