You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Nginx实现指定URL被访问时执行对应JavaScript文件

实现方案

可以实现,核心用Nginx的ngx_http_sub_module模块对指定路径的响应内容做字符串替换,注入script标签即可。


前置检查

先确认Nginx已安装ngx_http_sub_module,执行命令:

nginx -V 2>&1 | grep -- 'http_sub_module'

有输出说明模块可用,没有的话需要重新编译Nginx加上--with-http_sub_module参数。


修改后的完整配置

server {
    listen 443 ssl;
    server_name example.net;

    access_log      /var/log/nginx/example.net.ssl.access.log;
    error_log       /var/log/nginx/example.net.ssl.error.log;

    ssl_certificate         /etc/letsencrypt/live/example.net/cert.pem;
    ssl_certificate_key     /etc/letsencrypt/live/example.net/privkey.pem;

    # 配置本地JS文件的访问路径,让浏览器可以加载到你指定的file.js
    location = /inject-script.js {
        alias /path/to/file.js;
        # 可选:设置JS的缓存规则
        expires 1h;
        add_header Content-Type application/javascript;
    }

    # 精确匹配你要注入脚本的路径,只有访问这个路径才会触发替换
    location = /test/page {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # 禁用gzip压缩,否则Nginx无法解析响应内容做替换
        proxy_set_header Accept-Encoding "";
        proxy_pass http://localhost:8080;

        # 开启替换功能,在</body>标签前插入script标签加载你的JS
        sub_filter '</body>' '<script src="/inject-script.js"></script></body>';
        # 只替换一次即可
        sub_filter_once on;
        # 指定对HTML类型的响应做替换,避免影响其他静态资源
        sub_filter_types text/html;
    }

    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080;
    }
}

注意事项

  • 如果你的页面没有</body>标签,可以把替换目标改成</head>,效果一致,只是脚本执行时机提前。
  • 如果你不想单独配置JS的访问路径,也可以直接把JS代码写在注入的script标签里,比如:
    sub_filter '</body>' '<script>/* 你的JS代码直接写在这里 */</script></body>';
    
    适合短代码场景。
  • 配置修改后执行nginx -t检查语法,确认无误后执行nginx -s reload生效。

内容的提问来源于stack exchange,提问作者baked_cookies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:03