#!/usr/bin/env node /* ========================================================================== Nginx 专题 · 行为实测核验 用法:node tools/verify-behavior.js [镜像,默认 nginx:1.27-alpine] 为什么要有这个脚本:本站在多处写了「反直觉」的结论(location 优先级、proxy_pass 的 URI 替换、add_header 不合并继承、nginx 默认不传 X-Forwarded-For / 默认用 HTTP/1.0 回源、return 会丢掉原始查询串、同 location 里的 return 会不会绕过 limit_req / deny……)。这类结论最容易被旧文章带偏,所以这里用真实容器跑一遍, 把「记忆」换成「实测」,并把 error.log 当成证据一起打出来。 它做四件事: 1. 起一个 nginx 容器,注入一份专门覆盖上述行为的配置; 2. 从宿主机发请求,逐条比对状态码 / 响应头 / 响应体,并打印实测原值; 3. 采集 nginx -V(编译参数)、nginx -T(生效配置 → 确认默认值)与 error.log 关键行; 4. 退出码非 0 表示有结论与文档不符。 只用 Docker + Node(无第三方依赖)。没有可用 Docker 时跳过,不算失败。 ========================================================================== */ "use strict"; const { execFileSync, spawnSync } = require("child_process"); const fs = require("fs"); const os = require("os"); const path = require("path"); const IMAGE = process.argv[2] || "nginx:1.27-alpine"; const NAME = "nginx-kb-verify"; const PORT = Number(process.env.VERIFY_PORT || 18080); const BASE = `http://127.0.0.1:${PORT}`; const log = (...a) => console.log(...a); const docker = (args, opt) => execFileSync("docker", args, { encoding: "utf8", stdio: opt || "pipe" }); const sleep = ms => new Promise(r => setTimeout(r, ms)); /* ------------------------------ 1. 被测配置 ------------------------------ conf.d 下只留这一个文件,所以它就是 80 端口的默认 server,不依赖 Host 头。 后端是同一个容器里 127.0.0.1:8082 上的另一个 server,用来观察 nginx 回源时 到底发出去了什么(Host / XFF / 协议版本)。 */ const CONF = [ "# 限流区:vr 给 return 短路用,vr2 给真正的内容处理器用,两边互不干扰", "limit_req_zone $binary_remote_addr zone=vr:10m rate=1r/s;", "limit_req_zone $binary_remote_addr zone=vr2:10m rate=1r/s;", "", "# ---------- 后端:回显它收到的请求行与关键请求头 ----------", "server {", " listen 8082;", " server_name _;", " default_type text/plain;", " location / {", " return 200 \"BACKEND uri=$uri host=$http_host proto=$server_protocol xff=[$http_x_forwarded_for] realip=[$http_x_real_ip]\\n\";", " }", "}", "", "server {", " listen 80;", " server_name _;", " default_type text/plain;", " root /data;", " add_header X-Server \"srv\" always;", "", " # ---- A. location 匹配优先级 ----", " location = /m/exact { return 200 \"A-exact\\n\"; }", " location /m/exact { return 200 \"A-prefix\\n\"; }", " location ^~ /m/caret/sub { return 200 \"A-caret\\n\"; }", " location ~ ^/m/caret { return 200 \"A-regex\\n\"; }", " location ~ ^/m/re { return 200 \"A-re-first\\n\"; }", " location ~ ^/m/re/two { return 200 \"A-re-second\\n\"; }", " location /m/lp { return 200 \"A-lp-short\\n\"; }", " location /m/lp/deep { return 200 \"A-lp-deep\\n\"; }", " location /m/rp/deep/more { return 200 \"A-rp-prefix\\n\"; }", " location ~ ^/m/rp { return 200 \"A-rp-regex\\n\"; }", " location = /m/case { return 200 \"A-case-exact\\n\"; }", " location ~* ^/M/CASE { return 200 \"A-case-regex\\n\"; }", "", " # ---- B. root / alias ----", " location /m/root/ { }", " location /m/alias/ { alias /data/sub/; }", "", " # ---- C. try_files 前端路由兜底 ----", " location /m/spa/ { try_files $uri $uri/ /m/spa/index.html; }", "", " # ---- D. proxy_pass 的 URI 替换语义 ----", " location /pp/noslash/ { proxy_pass http://127.0.0.1:8082; }", " location /pp/slash/ { proxy_pass http://127.0.0.1:8082/; }", " location /pp/path/ { proxy_pass http://127.0.0.1:8082/base/; }", " location = /pp/exact { proxy_pass http://127.0.0.1:8082; }", "", " # ---- E. add_header 的继承与 always ----", " location = /h/plain { return 200 \"E-plain\\n\"; }", " location = /h/child { add_header X-Loc \"loc\"; return 200 \"E-child\\n\"; }", " location = /h/child404 { add_header X-Loc \"loc\"; return 404 \"E-404\\n\"; }", " location = /h/child404alw { add_header X-Loc \"loc\" always; return 404 \"E-404-always\\n\"; }", "", " # ---- F. $uri / $request_uri / $args ----", " location = /v/vars { return 200 \"uri=[$uri] request_uri=[$request_uri] args=[$args]\\n\"; }", "", " # ---- G. return / rewrite 的重定向与参数传递 ----", " location = /r/ret { return 301 /r/dest; }", " location = /r/retarg { return 301 /r/dest?from=ret; }", " location /r/dest { return 200 \"G-dest uri=[$uri] args=[$args]\\n\"; }", " location /r/rw/ { rewrite ^/r/rw/(.*)$ /r/dest/$1 last; }", "", " # ---- H. 限流:同一个 location 里 return 短路 vs 真正的内容处理器 ----", " location = /l/ret { limit_req zone=vr burst=2 nodelay; return 200 \"H-ret\\n\"; }", " location = /l/proxy { limit_req zone=vr2 burst=2 nodelay; proxy_pass http://127.0.0.1:8082; }", "", " # ---- J. 访问控制:deny 与 return 的先后 ----", " location = /a/denyret { deny all; return 200 \"J-deny-ret\\n\"; }", " location = /a/denyproxy { deny all; proxy_pass http://127.0.0.1:8082; }", " location = /a/denyfile { deny all; }", "", " # ---- K. expires 与 add_header Cache-Control 同时写 ----", " location = /i/exp { expires 1y; add_header Cache-Control \"public, max-age=31536000, immutable\" always; }", " location = /i/exp404 { expires 1y; return 404 \"K-404\\n\"; }", "", " # ---- I. 默认值探测:静态文件 / 大 body / gzip ----", " location / { try_files $uri =404; }", "}", "" ].join("\n"); const DATA = { "m/root/x.txt": "DATA-ROOT\n", "sub/x.txt": "DATA-ALIAS\n", "m/spa/index.html": "spaSPA-INDEX\n", "i/exp": "static file served with expires\n", "big.txt": "compressible line of text\n".repeat(400) }; /* ------------------------------ 2. 单发探针 ------------------------------ */ const PROBES = [ { g: "A location 匹配", name: "= 精确匹配优先于前缀匹配", path: "/m/exact", expect: { status: 200, body: "A-exact" } }, { g: "A location 匹配", name: "^~ 命中后不再尝试正则", path: "/m/caret/sub/deep", expect: { status: 200, body: "A-caret" } }, { g: "A location 匹配", name: "多个正则按书写顺序,先匹配者胜", path: "/m/re/two", expect: { status: 200, body: "A-re-first" } }, { g: "A location 匹配", name: "无正则命中时最长前缀胜", path: "/m/lp/deep/x", expect: { status: 200, body: "A-lp-deep" } }, { g: "A location 匹配", name: "正则优先于更长的前缀(没用 ^~ 时)", path: "/m/rp/deep/more/x", expect: { status: 200, body: "A-rp-regex" } }, { g: "A location 匹配", name: "= 精确匹配先于 ~* 不区分大小写正则", path: "/m/case", expect: { status: 200, body: "A-case-exact" } }, { g: "B root/alias", name: "root:把 location 前缀拼在磁盘路径前", path: "/m/root/x.txt", expect: { status: 200, body: "DATA-ROOT" } }, { g: "B root/alias", name: "alias:用 alias 路径替换掉 location 前缀", path: "/m/alias/x.txt", expect: { status: 200, body: "DATA-ALIAS" } }, { g: "B root/alias", name: "alias 被当成目录拼在磁盘路径后(不存在的组合即 404)", path: "/m/alias/m/root/x.txt", expect: { status: 404 } }, { g: "C try_files", name: "命中真实文件", path: "/m/spa/index.html", expect: { status: 200, body: "SPA-INDEX" } }, { g: "C try_files", name: "前端路由兜底到 index.html", path: "/m/spa/deep/link/42", expect: { status: 200, body: "SPA-INDEX" } }, { g: "D proxy_pass", name: "不带 URI:原样透传完整路径", path: "/pp/noslash/foo/bar", expect: { status: 200, body: "uri=/pp/noslash/foo/bar" } }, { g: "D proxy_pass", name: "带 /:location 前缀被替换为 /", path: "/pp/slash/foo/bar", expect: { status: 200, body: "uri=/foo/bar" } }, { g: "D proxy_pass", name: "带 /base/:前缀被替换为 /base/", path: "/pp/path/foo", expect: { status: 200, body: "uri=/base/foo" } }, { g: "D proxy_pass", name: "= 精确 location 透传原 URI", path: "/pp/exact", expect: { status: 200, body: "uri=/pp/exact" } }, { g: "D proxy_pass", name: "默认 Host 是 $proxy_host(后端看不到原始域名)", path: "/pp/noslash/foo", expect: { status: 200, body: "host=127.0.0.1:8082" } }, { g: "D proxy_pass", name: "默认回源协议是 HTTP/1.0", path: "/pp/noslash/foo", expect: { status: 200, body: "proto=HTTP/1.0" } }, { g: "D proxy_pass", name: "默认不发送 X-Forwarded-For / X-Real-IP", path: "/pp/noslash/foo", expect: { status: 200, body: "xff=[] realip=[]" } }, { g: "E add_header", name: "location 没写 add_header 时继承 server 级", path: "/h/plain", expect: { status: 200, headers: { "x-server": "srv" } } }, { g: "E add_header", name: "location 写了 add_header 后父级全部不继承", path: "/h/child", expect: { status: 200, headers: { "x-loc": "loc" }, headersAbsent: ["x-server"] } }, { g: "E add_header", name: "默认只对 2xx/3xx 生效,404 上加不上", path: "/h/child404", expect: { status: 404, headersAbsent: ["x-loc", "x-server"] } }, { g: "E add_header", name: "加 always 后错误响应也带", path: "/h/child404alw", expect: { status: 404, headers: { "x-loc": "loc" } } }, { g: "F 变量", name: "$uri 是解码归一化后的路径,$request_uri 是原始串", path: "/v/va%72s", expect: { status: 200, body: "uri=[/v/vars] request_uri=[/v/va%72s]" } }, { g: "F 变量", name: "$args 保留查询串", path: "/v/vars?a=1&b=2", expect: { status: 200, body: "args=[a=1&b=2]" } }, { g: "F 变量", name: "merge_slashes 默认开:重复斜杠先归一化再匹配", path: "/v//vars", expect: { status: 200, body: "uri=[/v/vars]" } }, { g: "G 重定向", name: "return 301 会丢掉原始查询串", path: "/r/ret?x=1", expect: { status: 301, locationHas: "/r/dest", locationLacks: "x=1" } }, { g: "G 重定向", name: "return 301 自带 ? 时以自带的为准", path: "/r/retarg?x=1", expect: { status: 301, locationHas: "/r/dest?from=ret" } }, { g: "G 重定向", name: "rewrite ... last 是内部跳转,客户端 URL 不变", path: "/r/rw/abc", expect: { status: 200, body: "G-dest uri=[/r/dest/abc]" } }, { g: "J 访问控制", name: "deny all 后接 return:return 先生效,deny 形同虚设", path: "/a/denyret", expect: { status: 200, body: "J-deny-ret" } }, { g: "J 访问控制", name: "deny all 配真正的内容处理器:正常 403", path: "/a/denyproxy", expect: { status: 403 } }, { g: "J 访问控制", name: "deny all 配静态文件处理器:正常 403", path: "/a/denyfile", expect: { status: 403 } }, { g: "I 默认值", name: "gzip 默认关闭(客户端声明支持也不压)", path: "/big.txt", sendGzip: true, expect: { status: 200, headersAbsent: ["content-encoding"] } }, { g: "I 默认值", name: "server_tokens 默认开:Server 头暴露版本号", path: "/big.txt", expect: { status: 200, headerMatch: { server: /^nginx\/\d+\.\d+\.\d+$/ } } }, { g: "I 默认值", name: "client_max_body_size 默认 1m:2MB 请求体被 413 拒绝", path: "/", method: "POST", bodyBytes: 2 * 1024 * 1024, expect: { status: 413 } }, { g: "K 缓存头", name: "expires 与 add_header Cache-Control 同写 → 发出两条 Cache-Control", path: "/i/exp", expect: { status: 200, headers: { "cache-control": "max-age=31536000, public, max-age=31536000, immutable" } } }, { g: "K 缓存头", name: "expires 只对 2xx/3xx 生效:404 上没有 Expires", path: "/i/exp404", expect: { status: 404, headersAbsent: ["expires", "cache-control"] } } ]; /* ------------------------------ 3. 工具 ------------------------------ */ const haveDocker = () => spawnSync("docker", ["version", "--format", "{{.Server.Version}}"], { encoding: "utf8" }).status === 0; const cleanup = () => spawnSync("docker", ["rm", "-f", NAME], { stdio: "ignore" }); async function waitReady() { for (let i = 0; i < 60; i++) { try { const r = await fetch(`${BASE}/__probe`, { redirect: "manual" }); if (r.status) return true; } catch (e) {} await sleep(500); } return false; } function buildConfDir() { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nginx-kb-")); fs.writeFileSync(path.join(dir, "verify.conf"), CONF, "utf8"); for (const [rel, content] of Object.entries(DATA)) { const p = path.join(dir, "data", rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, content, "utf8"); } return dir; } async function hit(p) { const init = { redirect: "manual", headers: {} }; if (p.sendGzip) init.headers["accept-encoding"] = "gzip, deflate, br"; if (p.method) init.method = p.method; if (p.bodyBytes) init.body = Buffer.alloc(p.bodyBytes, "a"); const res = await fetch(BASE + p.path, init); return { status: res.status, headers: res.headers, text: await res.text() }; } function observed(got) { return [ `status=${got.status}`, got.headers.get("location") ? `Location=${got.headers.get("location")}` : "", got.headers.get("content-encoding") ? `Content-Encoding=${got.headers.get("content-encoding")}` : "", `Server=${got.headers.get("server") || "-"}`, `X-Loc=${got.headers.get("x-loc") || "(无)"}`, `X-Server=${got.headers.get("x-server") || "(无)"}`, got.text.trim() ? `body=${JSON.stringify(got.text.trim().slice(0, 78))}` : "" ].filter(Boolean).join(" · "); } function check(p, got) { const e = p.expect, bad = []; if (e.status !== undefined && got.status !== e.status) bad.push(`状态码 ${got.status} ≠ ${e.status}`); if (e.body && !got.text.includes(e.body)) bad.push(`响应体缺 ${JSON.stringify(e.body)}(实际 ${JSON.stringify(got.text.trim().slice(0, 90))})`); if (e.headers) for (const [k, v] of Object.entries(e.headers)) { const g = got.headers.get(k); if (g !== v) bad.push(`头 ${k}: ${JSON.stringify(g)} ≠ ${JSON.stringify(v)}`); } if (e.headersAbsent) for (const k of e.headersAbsent) { const g = got.headers.get(k); if (g) bad.push(`不该出现 ${k},实际 ${JSON.stringify(g)}`); } if (e.locationHas !== undefined) { const g = got.headers.get("location") || ""; if (!g.includes(e.locationHas)) bad.push(`Location ${JSON.stringify(g)} 不含 ${JSON.stringify(e.locationHas)}`); } if (e.locationLacks !== undefined) { const g = got.headers.get("location") || ""; if (g.includes(e.locationLacks)) bad.push(`Location ${JSON.stringify(g)} 不该含 ${JSON.stringify(e.locationLacks)}`); } if (e.headerMatch) for (const [k, re] of Object.entries(e.headerMatch)) { if (!re.test(got.headers.get(k) || "")) bad.push(`头 ${k} 不匹配 ${re}(实际 ${got.headers.get(k)})`); } return bad; } /* ------------------------------ 4. 主流程 ------------------------------ */ (async function main() { if (!haveDocker()) { log("未检测到可用的 Docker daemon —— 跳过行为实测(站点本身不依赖它)。"); log("想跑核验:装好 Docker 后执行 node tools/verify-behavior.js"); process.exit(0); } log(`镜像 ${IMAGE} · 宿主端口 ${PORT} · 容器名 ${NAME}\n`); cleanup(); const dir = buildConfDir(); const mismatches = []; let total = 0; docker(["run", "-d", "--name", NAME, "-p", `${PORT}:80`, IMAGE]); try { if (!(await waitReady())) throw new Error("容器 20s 内没有就绪,请检查镜像能否正常启动"); docker(["cp", path.join(dir, "verify.conf"), `${NAME}:/etc/nginx/conf.d/verify.conf`]); docker(["cp", path.join(dir, "data"), `${NAME}:/data`]); docker(["exec", NAME, "rm", "-f", "/etc/nginx/conf.d/default.conf"]); docker(["exec", NAME, "nginx", "-t"]); docker(["exec", NAME, "nginx", "-s", "reload"]); await sleep(700); /* -------- 环境信息 -------- */ const ver = docker(["exec", NAME, "sh", "-c", "nginx -v 2>&1"]).trim().replace(/^nginx version:\s*/, ""); const confArgs = docker(["exec", NAME, "sh", "-c", "nginx -V 2>&1"]).replace(/\s+/g, " "); const builtins = (confArgs.match(/--with-([a-z0-9_+-]+)/g) || []).join(" "); log("── 版本与编译参数 ─────────────────────────────────────────────"); log(`版本 ${ver}`); log(`configure ${builtins || "(未解析到 --with-* 参数)"}`); const eff = docker(["exec", NAME, "nginx", "-T"]); log("生效配置(nginx -T)里与默认值相关的指令:"); for (const k of ["worker_processes", "worker_connections", "keepalive_timeout", "sendfile", "client_max_body_size", "gzip", "merge_slashes", "server_tokens"]) { const m = eff.match(new RegExp("^\\s*" + k + "\\s+[^;]+;", "m")); log(` ${m ? m[0].trim() : k + " —— 未显式出现,取编译默认值"}`); } log(""); /* -------- 单发探针 -------- */ let group = ""; for (const p of PROBES) { if (p.g !== group) { group = p.g; log(`── ${group} ${"─".repeat(Math.max(0, 58 - group.length))}`); } total++; let got, bad; try { got = await hit(p); bad = check(p, got); } catch (e) { bad = ["请求异常:" + e.message]; got = { status: "-", headers: new Headers(), text: "" }; } log(` ${bad.length ? "✗" : "✓"} ${p.name}`); log(` 实测 ${observed(got)}`); if (bad.length) { mismatches.push(p.name); bad.forEach(b => log(` → ${b}`)); } await sleep(110); } /* -------- 连发序列:limit_req -------- */ log(`── H 限流(连发 6 次) ${"─".repeat(38)}`); const seq = async (p, n) => { const out = []; for (let i = 0; i < n; i++) { const r = await fetch(BASE + p, { redirect: "manual" }); out.push(r.status); await r.text(); } return out; }; const retSeq = await seq("/l/ret", 6); const proxySeq = await seq("/l/proxy", 6); total += 2; const retOk = retSeq.every(s => s === 200); log(` ${retOk ? "✓" : "✗"} /l/ret(limit_req + return)连发 6 次 → [${retSeq.join(", ")}]`); log(` 说明:${retOk ? "全部放行 —— 同 location 的 return 在 rewrite 阶段就终结了请求,limit_req 所在的 preaccess 阶段根本没轮到" : "出现了拒绝,与预期不符"}`); if (!retOk) mismatches.push("limit_req + return 短路"); const okCount = proxySeq.filter(s => s === 200).length; const has503 = proxySeq.includes(503); const proxyOk = has503 && okCount <= 3; log(` ${proxyOk ? "✓" : "✗"} /l/proxy(limit_req + proxy_pass)连发 6 次 → [${proxySeq.join(", ")}]`); log(` 实测:放行 ${okCount} 个后被限流(rate=1r/s + burst=2 + nodelay)`); if (!proxyOk) mismatches.push("limit_req + 真实内容处理器"); /* -------- error.log 证据 -------- 注意:官方镜像把 /var/log/nginx/*.log 软链到了 /dev/stdout、/dev/stderr, 所以不能靠读容器里的文件,必须用 docker logs 抓它。 */ const link = docker(["exec", NAME, "sh", "-c", "readlink -f /var/log/nginx/error.log"]).trim(); const lg = spawnSync("docker", ["logs", NAME], { encoding: "utf8" }); const errlog = (lg.stdout || "") + (lg.stderr || ""); const evidence = errlog.split("\n").filter(l => /limiting requests|access forbidden|denied|excess/.test(l)); log(""); log("── error.log 关键行(谁真的被拦了) ───────────────────────────"); log(` 官方镜像的 error.log 指向 ${link}(所以只能用 docker logs 读)`); if (evidence.length) { [...new Set(evidence.map(l => l.replace(/^\S+ \S+ /, "")))].forEach(l => log(" " + l.trim())); } else { log(" (没有任何限流 / 拒绝记录)"); } log(""); if (mismatches.length) { console.error(`✗ ${mismatches.length}/${total} 条结论与实测不符,请修正站点正文后再交付:`); mismatches.forEach(m => console.error(" - " + m)); process.exitCode = 1; } else { log(`✓ 全部 ${total} 条结论均与 ${ver} 实测一致。`); } } finally { cleanup(); try { fs.rmSync(dir, { recursive: true, force: true }); } catch (e) {} } })();