feat: 每个资料子页面加回导航页的返回入口;导航页与 Docker/Linux/Nginx/408 站点入库
一、子页面返回入口(本次改动)
- 新增 assets/back.js:在页面顶栏的站点标题之后挂「← 资料库」,点一下回根目录
index.html 并直接落在本资料的详情路由(如 #/knowledge/docker);注册表之外的目录
(408/)回首页;没有顶栏的页面(408 的 404)退化为左下角浮动按钮
- 层级由脚本自己的 src 反推(new URL('../', src)),任何目录深度都不必改 back.js;
样式跟随各站点:描边 / 文字用 currentColor、主色用 var(--brand) / var(--accent)、
圆角跟随 var(--btn-radius),深浅色主题都自适应,打印时自动隐藏;页面里已有
index.html#/ 形式的返回链接时(interview/ 占位页)不再重复挂
- 新增 tools/add-back-links.js:按 assets/portal.data.js 反查路由与名称,给每个子页面
注入 <script src="…assets/back.js" data-portal-back=… data-portal-label=…>。
先删旧标签再按规则插回,位置写错也能自动纠正;--check 只检查(缺一个即退出码 1)、
--dry 只预演、写入失败不会中断整轮
- 共注入 454 个页面,3 个有意跳过:根 index.html(它本身就是导航页)、
interview/index.html(已有「← 返回导航」)、408/ds12-tree/og.html(分享预览图页面)
- 末尾是内联 <script> 的 7 个 index.html:标签插在内联脚本之前,保持
</script>\s*</body> 的既有形态,各站点自检规则不受影响
- .sre-s23/gen.js 的两处模板同步带上该行,重新生成 SRE 模块页不会丢入口
- README 补「子页面怎么回到导航页」一节,并在新增资料流程里加上这一步
二、此前未入库的内容(一并提交)
- 导航页:index.html + assets/portal.css|portal.data.js|portal.js + tools/check-portal.js
- knowledge/docker(14 章)、knowledge/linux(17 章)、knowledge/nginx(17 章)
- 408/ds12-tree 知识卡片(app.js / styles.css / verify.mjs / favicon / og)
- interview 占位页、README.md
校验
- add-back-links --check:454 / 454 已就绪
- check-portal:3 个模块 / 6 份资料全部命中(无死链)
- check-pages:docker 15 页、linux 18 页、nginx 18 页、sre-learning-path 399 页 全部 OK
- 无头 Chrome 实测点击:docker 章节页 / SRE 模块页 / 场景题库 / 项目题库 / 408 卡片页
都落到对应资料详情,404 的浮动按钮回导航首页;按钮颜色浅色 rgb(23,33,46) 深色
rgb(231,237,246) 自适应,408 站点圆角保持 0px
- 受版本管理的 402 个页面每个只 +1 行(gen.js +2 行),没有整文件改写
说明:本机沙箱下 knowledge/sre-learning-path/**、408/、knowledge/scenario、project/、
interview/ 这些文件当时不可写(缺低完整性标记),注入是在一次完全权限授权下完成的。
This commit is contained in:
291
knowledge/nginx/tools/SPEC.md
Normal file
291
knowledge/nginx/tools/SPEC.md
Normal file
@@ -0,0 +1,291 @@
|
||||
# Nginx 专题知识库 · 章节写作规范(SPEC)
|
||||
|
||||
> 本文件是写章节正文的**唯一契约**。骨架(侧栏目录树、上下章导航、页脚)由
|
||||
> `tools/build-nav.js` 统一生成,你只需要写正文,**不要自己写目录树**。
|
||||
> 写完必须能通过 `node tools/check-pages.js`。站点根目录:`knowledge/nginx/`。
|
||||
|
||||
## 0. 定位
|
||||
|
||||
- 读者:有 1–3 年经验的开发者 / 运维,日常要用 nginx 做本地联调代理、服务发布、HTTPS、
|
||||
灰度切流,也要在半夜收到 502/504 告警时定位问题。
|
||||
- 立场:**面向实际开发与生产使用**——每个知识点都要回答「我在什么时候会用到它、配错了会怎样」。
|
||||
- 语气:直接、具体、讲代价。不写「nginx 性能很高」这类空话;给配置、给输出、给判断依据。
|
||||
- 篇幅:每章正文 2500–4500 字(含配置),小节 3–10 个,每个小节 2–6 段或「段落 + 配置 + 提示框」。
|
||||
- 一句话区别:**nginx 的知识点几乎全是「配置语义」**,所以本站的重点是「这条指令到底怎么算的」,
|
||||
而不是罗列参数。
|
||||
|
||||
## 1. 文件模板(严格照抄结构,只替换标题与正文)
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>第 4 章 进程模型与请求处理阶段 · Nginx 专题知识库</title>
|
||||
<meta name="description" content="本章 40–80 字的摘要,写清覆盖范围与产出。">
|
||||
<meta name="keywords" content="关键词1 关键词2 关键词3 关键词4">
|
||||
<link rel="stylesheet" href="assets/doc.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="topbar">
|
||||
<div class="tb-in">
|
||||
<a class="brand" href="index.html"><span class="logo">NGX</span><div>Nginx 专题<small>从开发联调到生产运维</small></div></a>
|
||||
<div class="crumbs">
|
||||
<a href="index.html">总目录</a><span class="sep">/</span><b>第 4 章</b>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<button class="btn" id="tocToggle">☰ 导航</button>
|
||||
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="layout" id="layout">
|
||||
<aside class="sidebar">
|
||||
<h2>章节目录</h2>
|
||||
<nav id="chapters"></nav>
|
||||
<div class="side-foot">
|
||||
<a class="btn" href="index.html">← 总目录</a>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="mask" id="mask"></div>
|
||||
|
||||
<main class="main-col">
|
||||
<article>
|
||||
<p class="chapnav"></p>
|
||||
|
||||
<h2 id="ch4"><span class="n">4</span>进程模型与请求处理阶段:nginx 为什么快、指令什么时候生效</h2>
|
||||
|
||||
<div class="lead">
|
||||
<b>这一章解决什么:</b>……(2–4 行,说明学完能做什么、为什么重要)
|
||||
</div>
|
||||
|
||||
<h3 id="sec-4-1">4.1 master 与 worker:谁在干活</h3>
|
||||
<p>……</p>
|
||||
|
||||
<!-- 更多小节 -->
|
||||
</article>
|
||||
|
||||
<nav class="pager"></nav>
|
||||
|
||||
<p class="foot"></p>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<button id="toTop" title="回到顶部">↑</button>
|
||||
<script src="assets/doc.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
四个空占位块**必须**原样保留(`<nav id="chapters"></nav>`、`<p class="chapnav"></p>`、
|
||||
`<nav class="pager"></nav>`、`<p class="foot"></p>`),内容由生成器填。
|
||||
|
||||
## 2. 可用的排版组件(只能用这些类,不要引入新 CSS)
|
||||
|
||||
| 组件 | 写法 | 用途 |
|
||||
|---|---|---|
|
||||
| 导语 | `<div class="lead">…</div>` | 每章开头一个,说明本章解决什么 |
|
||||
| 提示框 | `<div class="box note\|tip\|warn\|danger\|ok\|case">` + `<span class="bt">标题</span>` | note=补充说明,tip=技巧,warn=注意,danger=踩坑/事故,ok=推荐做法,case=真实案例 |
|
||||
| 配置/代码块 | `<pre data-lang="nginx" data-name="可选说明">…</pre>` | 语言标签自动显示并可一键复制;**每个 pre 必须带 data-lang** |
|
||||
| 表格 | `<div class="tablewrap"><table><thead>…</thead><tbody>…</tbody></table></div>` | 对比、速查、参数表 |
|
||||
| 步骤 | `<ol class="steps"><li>…</li></ol>` | 操作流程 |
|
||||
| 卡片 | `<div class="cards"><div class="card"><h4>…</h4><ul>…</ul></div></div>` | 并列要点 |
|
||||
| 行内 | `<code>` `<kbd>` `<mark>` `<strong>` | 指令、按键、重点 |
|
||||
| 小节标题 | `<h3 id="sec-4-1">4.1 标题</h3>` | **每个 h3 都必须有 id,格式 sec-章号-序号** |
|
||||
| 章标题 | `<h2 id="ch4"><span class="n">4</span>标题</h2>` | 每章一个,放正文最前面 |
|
||||
|
||||
`data-lang` 允许的值(**只有这些**,两个校验器用的是同一份列表):
|
||||
`bash` `shell` `sh` `console` `text` `yaml` `yml` `json` `dockerfile` `go` `javascript` `js`
|
||||
`typescript` `ts` `python` `java` `sql` **`nginx`** `ini` `toml` `conf` `lua` `powershell`
|
||||
`http` `makefile` `dockerignore` `properties` `xml` `csv` `promql`。
|
||||
**nginx 配置一律用 `data-lang="nginx"`;HTTP 报文用 `http`;命令行用 `bash`;JSON 日志用 `json`。**
|
||||
|
||||
## 3. 硬性规则(校验器会逐条检查,违反即失败)
|
||||
|
||||
1. 只创建分配给你的 `NN-*.html` 文件,**不要动** `index.html`、`assets/`、`tools/`、别人的章节。
|
||||
2. `<pre>` 内的 `<` 必须写成 `<`,`&` 写成 `&`,`>` 建议写成 `>`;
|
||||
配置块里出现 `$` 变量不用转义(原样写 `$uri`)。
|
||||
3. 标签必须闭合,`div/section/article/aside/nav/main/table/ul/ol/li/details` 开合数量一致。
|
||||
4. 站内链接只能指向本目录的文件或页内锚点;**不要写跨资料目录的相对路径**(不要 `../`)。
|
||||
指向别的章节的写法固定为 `06-proxy.html`、`06-proxy.html#sec-6-1`。
|
||||
5. 每个 `<h3>` 都要有 `id`,且以 `sec-<章号>-` 开头,**id 序号要与标题文本里的编号一致**、
|
||||
**从 1 连续排到 n 不能跳号**:`<h3 id="sec-4-2">4.2 标题</h3>`。
|
||||
(校验器会逐个比对 `sec-4-2` ↔ `4.2`,并检查 4.1→4.2→4.3 连续。)
|
||||
6. 小节数量 3–10 个;**正文(不含配置块)不少于 2800 字**;至少 3 个配置/代码块、
|
||||
至少 1 个表格或卡片组、至少 1 个 `.box` 提示框、至少 1 处「实战/实际用法」落点。
|
||||
另外每章都必须有:`<title>` 里含「第 N 章」、`meta description`(≥20 字)、
|
||||
`meta keywords`(≥6 字)、topbar 品牌区、`<div class="lead">`。
|
||||
7. 配置与命令必须真实可用:指令名、变量名、参数取值都要是 nginx 真实存在的
|
||||
(不确定就查官方文档,不要编造指令)。版本语境以 **nginx 1.27.x / 1.26.x** 为准。
|
||||
8. 术语:第一次出现的英文术语用「中文(English)」;指令、文件名一律 `<code>`。
|
||||
9. 不要写「如下图所示」——本站不放图片;用表格/列表替代。
|
||||
10. 每章至少包含一处「开发或运维中的实际用法」,用 `.box case` 案例或专门小节承载。
|
||||
11. **凡涉及本 SPEC 第 6 节「已实测核验的结论」的内容,必须与该节的实测结果一致**,
|
||||
不要照抄网上「据说」的说法。
|
||||
|
||||
## 4. 内容质量要求
|
||||
|
||||
- **先讲为什么**:任何指令先给场景(「为什么 `proxy_set_header Host` 不配就会把域名丢掉」),
|
||||
再给结论和配置。
|
||||
- **给判断依据**:不要只说「建议开 gzip」,要说清压缩比、CPU 代价、对已压缩资源无意义、
|
||||
以及 `gzip_static` 与 `brotli` 的选择。
|
||||
- **给排错路径**:每个易错点写清「现象 → 原因 → 验证命令 → 解决」。
|
||||
- **关联开发流程**:能联系到写代码、本地联调、CI、发布、上线、值班的地方就明确写出来
|
||||
(例如「本地 `proxy_pass` 不带斜杠导致 404」「reload 不断连接的原理」「灰度按权重切流」)。
|
||||
- **交叉引用**:涉及别章内容时用链接,例如「location 匹配算法见 <a href="03-config.html">第 3 章</a>」。
|
||||
|
||||
## 5. 全部 17 章大纲(只写分配给你的章,标题可微调但主语别变)
|
||||
|
||||
| 文件 | 章标题 | 小节大纲 |
|
||||
|---|---|---|
|
||||
| `01-what.html` | Nginx 全景与选型 | 1.1 一个真实痛点:单机扛住上万并发;1.2 同步阻塞 vs 事件驱动:省内存的代价;1.3 master/worker/cache 三类进程;1.4 nginx 的四类角色(静态服务/反向代理/负载均衡/网关);1.5 版本谱系:mainline vs stable、开源版 vs Plus、OpenResty/Tengine;1.6 与 Apache/Caddy/HAProxy/Envoy/Traefik 的边界:什么时候不该用 nginx;1.7 典型部署形态 |
|
||||
| `02-install.html` | 安装、目录布局与运行控制 | 2.1 四种安装方式与选型;2.2 源码编译与 configure 参数取舍;2.3 目录布局与运行时文件;2.4 命令行与信号(-t/-T/-s/-V、HUP/USR1/USR2/WINCH/QUIT);2.5 平滑升级与热二进制替换;2.6 systemd 托管;2.7 容器里跑 nginx;2.8 安装后自检清单 |
|
||||
| `03-config.html` | 配置结构、指令继承与 location 匹配 | 3.1 分层结构与 include;3.2 指令继承与覆盖规则;3.3 http/server/location 三层职责;3.4 location 匹配算法与实测优先级;3.5 location 误用与正确写法;3.6 server_name 匹配顺序与 default_server;3.7 变量体系;3.8 用 -t/-T 调试配置;3.9 多站点配置组织 |
|
||||
| `04-arch.html` | 进程模型与请求处理阶段 | 4.1 master 与 worker 的职责;4.2 事件驱动与多路复用;4.3 worker_processes/affinity/accept_mutex;4.4 请求处理 11 个阶段;4.5 rewrite 阶段 vs access/preaccess(return 短路实测);4.6 连接、请求与 keepalive;4.7 共享内存区;4.8 reload 为什么不断连接 |
|
||||
| `05-static.html` | 静态资源服务与缓存头 | 5.1 root 与 alias 的语义差异;5.2 try_files 与 SPA 兜底;5.3 索引与 autoindex;5.4 MIME 与 default_type;5.5 sendfile/tcp_nopush/tcp_nodelay/aio;5.6 gzip 与 brotli 取舍、gzip_static;5.7 expires/Cache-Control/ETag/条件请求;5.8 前端产物发布实战(hash 长缓存 + index 不缓存);5.9 静态服务常见坑 |
|
||||
| `06-proxy.html` | 反向代理核心:proxy_pass 的完整语义 | 6.1 proxy_pass 的 URI 替换规则(四种写法实测);6.2 请求头传递与 Host/XFF/X-Real-IP;6.3 proxy_set_header 默认值实测;6.4 proxy_http_version 与长连接复用;6.5 缓冲与流式;6.6 WebSocket 与 SSE;6.7 gRPC 代理;6.8 realip 与 X-Forwarded-Proto;6.9 动态上游(resolver / 变量 / Docker / K8s);6.10 代理排错清单 |
|
||||
| `07-lb.html` | 负载均衡与上游健康管理 | 7.1 upstream 结构与 server 参数;7.2 五种调度策略;7.3 被动健康检查与 proxy_next_upstream;7.4 主动健康检查的替代方案;7.5 upstream keepalive 连接池;7.6 会话保持的三种做法;7.7 灰度、蓝绿与按比例切流;7.8 负载均衡故障与排障 |
|
||||
| `08-tls.html` | HTTPS / TLS 与证书治理 | 8.1 TLS 握手与关键决策;8.2 证书链、SNI 与多域名;8.3 协议版本与加密套件;8.4 会话复用;8.5 HSTS、OCSP stapling 与安全头;8.6 ACME 自动签发续期;8.7 双向认证 mTLS;8.8 HTTPS 性能;8.9 证书过期事故与监控 |
|
||||
| `09-rewrite.html` | 变量、rewrite 与进阶路由 | 9.1 return 与 rewrite 的语义差异(参数处理实测);9.2 rewrite 的四个 flag;9.3 if 的真相与替代方案;9.4 map 把条件逻辑搬出 if;9.5 常见重定向需求(去 www/强制 https/尾斜杠/大小写);9.6 正则捕获与命名捕获;9.7 内部跳转、error_page 与 named location;9.8 路由改造的安全边界 |
|
||||
| `10-security.html` | 访问控制、限流限速与安全加固 | 10.1 威胁模型;10.2 allow/deny/geo/map 做 IP 策略(return 绕过 deny 实测);10.3 auth_basic 与 auth_request;10.4 limit_req 的 rate/burst/nodelay(实测语义);10.5 limit_conn 与 limit_rate;10.6 请求体与请求头限制;10.7 防盗链、防爬与 UA 治理;10.8 敏感文件与信息泄露;10.9 安全响应头与 CSP;10.10 上线前安全检查清单 |
|
||||
| `11-cache.html` | 缓存体系:proxy_cache 与微缓存 | 11.1 该不该在 nginx 做缓存;11.2 proxy_cache_path 参数与磁盘布局;11.3 cache key 设计与 Vary;11.4 有效期、stale-while-revalidate / stale-if-error;11.5 缓存绕过与清理;11.6 微缓存抗突发;11.7 fastcgi/uwsgi/scgi 缓存;11.8 命中率观测与失效问题 |
|
||||
| `12-log.html` | 日志体系与可观测性 | 12.1 access_log 与 error_log 的职责边界;12.2 log_format 与变量设计;12.3 JSON 结构化日志;12.4 $upstream_* 变量与耗时归因;12.5 日志切割与 USR1;12.6 缓冲、条件日志与性能代价;12.7 接 ELK/Loki/ClickHouse;12.8 stub_status 与 Prometheus;12.9 日志里的排障信号 |
|
||||
| `13-perf.html` | 性能调优与协议演进 | 13.1 调优方法论:先测量;13.2 worker 与连接数算法;13.3 缓冲区与超时参数;13.4 内核参数与文件描述符;13.5 HTTP/1.1 keepalive、HTTP/2、HTTP/3 取舍;13.6 静态资源性能组合拳;13.7 压测方法与指标解读;13.8 性能反模式;13.9 容量估算与压测清单 |
|
||||
| `14-ops.html` | 生产运维、发布与排障手册 | 14.1 配置管理与变更流程;14.2 平滑 reload 与灰度上线;14.3 高可用与 VIP/云 LB;14.4 状态码全景与归因;14.5 502/504/499 排障剧本;14.6 连接数与 fd 耗尽;14.7 磁盘与缓存目录治理;14.8 监控告警指标与阈值;14.9 事故复盘与 on-call 清单 |
|
||||
| `15-devtools.html` | 开发场景实战:把 Nginx 用进日常 | 15.1 本地开发为什么需要 nginx;15.2 前后端联调代理;15.3 CORS 的正确配法;15.4 本地 HTTPS 与域名映射;15.5 Mock 与接口分流;15.6 多环境/多分支并行;15.7 Docker Compose 里的 nginx;15.8 Kubernetes Ingress 与 nginx;15.9 可直接用的开发配置模板 |
|
||||
| `16-cheat.html` | 速查表与高频坑 | 16.1 命令与信号速查;16.2 配置片段速查;16.3 常用变量表;16.4 状态码速查与归因;16.5 20 个高频坑(现象→原因→解决);16.6 一条命令排障表;16.7 默认值速查(附实测) |
|
||||
| `17-checklist.html` | 能力自测、面试问答与继续深入 | 17.1 能力自测清单(三档);17.2 40 道自测题(附答案);17.3 面试高频问答与追问;17.4 学习路径(3 天 / 2 周 / 1 月);17.5 官方文档地图与延伸阅读 |
|
||||
|
||||
## 6. 已实测核验的结论(写这些内容时必须一致)
|
||||
|
||||
以下结论由 `node tools/verify-behavior.js` 在 **nginx/1.27.5(官方 `nginx:1.27-alpine` 镜像)**
|
||||
上实测得出,全部 38 条通过。写正文时请直接引用实测结论,**不要**照抄与之冲突的流行说法。
|
||||
|
||||
### 6.1 location 匹配优先级(实测)
|
||||
|
||||
1. `=` 精确匹配最先判断,命中即停;
|
||||
2. `^~` 前缀匹配命中后,**不再尝试任何正则**;
|
||||
3. 正则 `~` / `~*` **按配置文件里出现的先后顺序**逐个尝试,**第一个匹配的即胜出**
|
||||
(不是「更长的正则赢」);
|
||||
4. 都没命中时,用**最长**的普通前缀匹配。
|
||||
|
||||
实测示例:`location /m/rp/deep/more`(更长前缀)与 `location ~ ^/m/rp`(正则)同时存在时,
|
||||
请求 `/m/rp/deep/more/x` 命中**正则** —— 正则优先于更长的前缀,除非前缀写了 `^~`。
|
||||
|
||||
### 6.2 root 与 alias(实测)
|
||||
|
||||
- `root`:`磁盘路径 = root + 完整 URI`。`location /m/root/` + `root /data` → `/data/m/root/x.txt`。
|
||||
- `alias`:`磁盘路径 = alias 值 + URI 去掉 location 前缀后的部分`。
|
||||
`location /m/alias/` + `alias /data/sub/` → `/data/sub/x.txt`。
|
||||
|
||||
### 6.3 proxy_pass 的 URI 替换(实测)
|
||||
|
||||
| 写法 | 请求 | 后端收到的 URI |
|
||||
|---|---|---|
|
||||
| `location /pp/noslash/` + `proxy_pass http://127.0.0.1:8082;`(不带 URI) | `/pp/noslash/foo/bar` | `/pp/noslash/foo/bar`(原样透传) |
|
||||
| `location /pp/slash/` + `proxy_pass http://127.0.0.1:8082/;` | `/pp/slash/foo/bar` | `/foo/bar`(前缀被替换成 `/`) |
|
||||
| `location /pp/path/` + `proxy_pass http://127.0.0.1:8082/base/;` | `/pp/path/foo` | `/base/foo` |
|
||||
| `location = /pp/exact` + `proxy_pass http://127.0.0.1:8082;` | `/pp/exact` | `/pp/exact` |
|
||||
|
||||
口诀:**`proxy_pass` 后面只要带了 URI(哪怕只有一个 `/`),location 前缀就会被替换掉。**
|
||||
|
||||
### 6.4 回源请求的默认值(实测)
|
||||
|
||||
- 默认 `proxy_http_version` 是 **1.0**(后端 `$server_protocol` = `HTTP/1.0`);
|
||||
- 默认 `Host` 是 **`$proxy_host`**,即后端看到的是 `127.0.0.1:8082` 这类上游地址,
|
||||
**不是**原始域名 → 多租户/虚拟主机后端会路由错;
|
||||
- 默认**不发送** `X-Forwarded-For` / `X-Real-IP` → 后端拿到的客户端 IP 是 nginx 的 IP。
|
||||
|
||||
### 6.5 add_header 的继承(实测)
|
||||
|
||||
- `add_header` **不做合并式继承**:只要子级(location)里写了**任意一个** `add_header`,
|
||||
父级(server/http)里的**全部** `add_header` 都失效;
|
||||
- 默认只对 **2xx/3xx** 响应生效,404/403/502 等错误响应上**不加**;
|
||||
需要错误响应也带,必须写 `always`。
|
||||
|
||||
### 6.6 return / rewrite 与查询串(实测)
|
||||
|
||||
- `return 301 /r/dest;` 请求 `/r/ret?x=1` → 实测 `Location: http://127.0.0.1/r/dest`
|
||||
—— **原始查询串被丢掉**(与不少文章的说法相反),且 nginx 默认 `absolute_redirect on`,
|
||||
会把 Location 补成**绝对地址**;补的端口来自 nginx 自己的 `listen` 端口(这里是 80),
|
||||
不是客户端的 `Host` 端口 —— 这在容器/反向代理后面会造成跳转到错误地址。
|
||||
- `return 301 /r/dest?from=ret;` → `Location` 用自带的 `?from=ret`。
|
||||
- `rewrite ... last` 是**内部跳转**,客户端 URL 不变。
|
||||
|
||||
### 6.7 变量与路径归一化(实测)
|
||||
|
||||
| 请求 | `$uri` | `$request_uri` |
|
||||
|---|---|---|
|
||||
| `/v/va%72s` | `/v/vars`(已解码) | `/v/va%72s`(原始串) |
|
||||
| `/v//vars?a=1&b=2` | `/v/vars`(`merge_slashes` 默认开) | `/v//vars?a=1&b=2` |
|
||||
|
||||
即:**location 匹配和 `$uri` 用的是解码、归一化之后的路径;`$request_uri` 是客户端原始串。**
|
||||
|
||||
### 6.8 `return` 会短路掉后续阶段(实测,安全相关)
|
||||
|
||||
- 同一个 location 里 `limit_req ...; return 200 "ok";` → 连发 6 次**全部 200**,
|
||||
`error.log` 里**没有任何** `limiting requests` 记录。
|
||||
- 同一个 location 里 `deny all; return 200 "ok";` → 实测返回 **200**(不是 403),
|
||||
`error.log` 里**没有** `access forbidden` 记录。
|
||||
- 换成真正的内容处理器(`proxy_pass` / 静态文件)后,`limit_req` 与 `deny all` 都正常生效:
|
||||
`limit_req` 连发 6 次得到 `[200,200,200,503,503,503]`,`deny all` 得到 403。
|
||||
|
||||
原因:`return` 在 **rewrite 阶段(NGX_HTTP_REWRITE_PHASE)** 就终结了请求,
|
||||
而 `limit_req` / `limit_conn` 在 **preaccess 阶段**、`allow/deny` 在 **access 阶段**,
|
||||
都排在 rewrite 之后,根本没轮到。所以**不要把 `return` 和访问控制/限流写在同一个 location 里
|
||||
还指望访问控制生效**。
|
||||
|
||||
### 6.9 limit_req 的 burst 语义(实测)
|
||||
|
||||
`limit_req_zone ... rate=1r/s;` + `limit_req zone=... burst=2 nodelay;`
|
||||
连续 6 个请求 → `[200, 200, 200, 503, 503, 503]`:
|
||||
**放行数 = 1(速率名额)+ burst**,`nodelay` 让排队的请求立即被拒而不是延迟处理。
|
||||
|
||||
### 6.10 其他默认值(实测)
|
||||
|
||||
- `gzip` 默认 **off**(客户端发 `Accept-Encoding: gzip` 也不压);
|
||||
- `server_tokens` 默认 **on**:`Server: nginx/1.27.5` 带版本号;
|
||||
- `client_max_body_size` 默认 **1m**:2MB 请求体直接被 **413**;
|
||||
- 官方镜像的 `nginx.conf` 显式写了 `keepalive_timeout 65;`、`worker_processes auto;`、
|
||||
`worker_connections 1024;`、`sendfile on;`(**编译默认值**是 `keepalive_timeout 75s`);
|
||||
- 官方镜像 `nginx:1.27-alpine` 的编译参数包含 `--with-http_ssl_module`、`--with-http_v2_module`、
|
||||
`--with-http_v3_module`、`--with-http_realip_module`、`--with-http_stub_status_module`、
|
||||
`--with-http_gzip_static_module`、`--with-http_slice_module`、`--with-stream`、
|
||||
`--with-stream_ssl_preread_module` 等(`nginx -V` 实测);
|
||||
- 官方镜像把 `/var/log/nginx/error.log`、`access.log` 软链到 `/dev/stdout`、`/dev/stderr`,
|
||||
所以**读日志要用 `docker logs`,不是读容器里的文件**;
|
||||
- HTTP/2 的开启写法:**`http2 on;`**(放在 `server` 里)是当前写法;
|
||||
旧的 `listen 443 ssl http2;` 在 1.27.5 上仍能用,但会打一条
|
||||
`the "listen ... http2" directive is deprecated, use the "http2" directive instead` 的 **warn**。
|
||||
写正文时用 `http2 on;`,并可以提一句旧写法已废弃。
|
||||
- `nginx -t` 只校验语法;`nginx -s reload` 在**配置有错时会保留旧配置继续服务**,
|
||||
所以「reload 命令执行成功」不等于「新配置生效」——必须先 `-t` 再 reload,并用 `nginx -T` 或行为验证确认。
|
||||
- `expires` 与 `add_header Cache-Control` **同时写会发出两条 `Cache-Control` 响应头**(实测 200 响应里
|
||||
同时有 `Cache-Control: max-age=31536000`(来自 `expires 1y`)与 `Cache-Control: public, max-age=31536000, immutable`(来自 `add_header`))。
|
||||
另外 `expires` **只对 2xx/3xx 生效**(实测 404 响应上既没有 `Expires` 也没有它带来的 `Cache-Control`),
|
||||
所以想让错误响应也带缓存/安全头,只能靠 `add_header ... always`。
|
||||
- `ssl_protocols` 的**编译默认值就是 `TLSv1.2 TLSv1.3`**,不需要显式写:
|
||||
官方 CHANGES 记录 1.23.4「now TLSv1.3 protocol is enabled by default」、
|
||||
1.27.3「now TLSv1 and TLSv1.1 protocols are disabled by default」;
|
||||
实测也证实——不写 `ssl_protocols` 时(`nginx -T` 里根本不出现该指令),
|
||||
客户端默认协商结果是 **TLSv1.3 / TLS_AES_256_GCM_SHA384**,而 TLSv1、TLSv1.1 均被拒绝。
|
||||
(验证技巧:用 `openssl s_client -tls1_3` 时输出行是 `New, TLSv1.3, Cipher is ...`,
|
||||
**不是** `Protocol : ...`,别因为 grep 不到 `Protocol` 就以为 TLS 1.3 没开。)
|
||||
- `error_page` 有**作用域陷阱**(第 10 章实测):把 `error_page 403 /x;` 写在 `server` 层,
|
||||
会接管该 server 下**所有** 403,`.env` / `.git/config` / `backup.sql` 这类敏感文件
|
||||
会从 403 变成 302 —— 巡检脚本因此不能只判断「不是 200」。
|
||||
- `rewrite ... break` 与 `return` **不同**:`return` 会短路掉 `limit_req`(见 6.8),
|
||||
而 `rewrite ... break` 实测**照常被限流计数**。
|
||||
|
||||
## 7. 交付前的自检
|
||||
|
||||
```bash
|
||||
cd knowledge/nginx
|
||||
node tools/check-chapter.js 04-arch.html # 单章自检(写的时候用,反馈最快)
|
||||
node tools/build-nav.js # 重建侧栏 / 定位条 / 上下章 / 目录页卡片与指标
|
||||
node tools/check-pages.js # 全站自检:结构、链接、锚点、转义、节数、篇幅
|
||||
```
|
||||
|
||||
只写自己那几章时可以只跑 `node tools/check-pages.js`;如果报错指向的不是你的文件,忽略即可。
|
||||
178
knowledge/nginx/tools/build-nav.js
Normal file
178
knowledge/nginx/tools/build-nav.js
Normal file
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Nginx 专题 · 页面骨架生成器
|
||||
用法:node tools/build-nav.js [站点根目录,默认本文件的上一级]
|
||||
|
||||
作用:扫描站点根目录下的 NN-*.html,采集「章标题(h2)+ 小节(h3)」与
|
||||
每章的 <meta name="description">,然后重写页面里的占位区块:
|
||||
|
||||
章节页:<nav id="chapters"></nav> 侧栏目录树(当前章展开小节)
|
||||
<p class="chapnav"></p> 「第 N / 14 章」定位条
|
||||
<nav class="pager"></nav> 上一章 / 下一章
|
||||
<p class="foot"></p> 页脚
|
||||
目录页:<nav id="chapters"></nav> 全部章节(不展开小节)
|
||||
<!-- AUTO:kpis --> 章节 / 小节 / 代码示例 / 字数 四块指标
|
||||
<!-- AUTO:cards --> 章节卡片(勾选已读 + 展开小节链接)
|
||||
<nav class="pager"></nav> 「开始阅读」
|
||||
<p class="foot"></p>
|
||||
|
||||
写章节时只写正文,骨架由本脚本统一生成;新增/重排章节后重新执行即可,
|
||||
幂等、可重复运行。
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = process.argv[2] || path.resolve(__dirname, "..");
|
||||
|
||||
const esc = s => String(s).replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
|
||||
const decode = s => s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"')
|
||||
.replace(/'/g, "'").replace(/ /g, " ").replace(/&/g, "&");
|
||||
const plain = s => decode(stripTags(s));
|
||||
const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
|
||||
|
||||
/* ---------------------------- 1. 采集 ---------------------------- */
|
||||
const files = fs.readdirSync(root, { withFileTypes: true })
|
||||
.filter(e => e.isFile() && /^\d\d-.*\.html$/.test(e.name))
|
||||
.map(e => e.name).sort();
|
||||
|
||||
if (!files.length) {
|
||||
console.error("没有找到 NN-*.html 章节页,请检查目录:" + root);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const chapters = files.map(file => {
|
||||
const html = fs.readFileSync(path.join(root, file), "utf8");
|
||||
const num = parseInt(file.slice(0, 2), 10);
|
||||
|
||||
const h2 = html.match(/<h2 id="[^"]*">([\s\S]*?)<\/h2>/);
|
||||
if (!h2) throw new Error(`${file}: 找不到 <h2 id="...">章标题</h2>`);
|
||||
const title = plain(h2[1].replace(/<span class="n">\d+<\/span>/, ""));
|
||||
|
||||
const sections = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
|
||||
.map(m => ({ id: m[1], label: plain(m[2]) }));
|
||||
|
||||
const metaDesc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
const metaKeys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
|
||||
const article = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1];
|
||||
// 正文字数不含代码块(代码块单独统计段数)
|
||||
const bodyText = article.replace(/<pre[\s\S]*?<\/pre>/g, " ");
|
||||
|
||||
return {
|
||||
num, file, title, sections,
|
||||
desc: plain(metaDesc),
|
||||
keywords: plain(metaKeys),
|
||||
pres: (html.match(/<pre[\s\S]*?<\/pre>/g) || []).length,
|
||||
chars: plain(bodyText).replace(/\s+/g, "").length
|
||||
};
|
||||
});
|
||||
|
||||
const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0);
|
||||
const totalPres = chapters.reduce((n, c) => n + c.pres, 0);
|
||||
const totalChars = chapters.reduce((n, c) => n + c.chars, 0);
|
||||
|
||||
/* ---------------------------- 2. 区块生成 ---------------------------- */
|
||||
function navTree(curNum) {
|
||||
return chapters.map(c => {
|
||||
const isCur = c.num === curNum;
|
||||
const row = isCur
|
||||
? `<span class="toc-a active" aria-current="page"><i class="cn">${c.num}</i>${esc(c.title)}</span>`
|
||||
: `<a class="toc-a" href="${c.file}"><i class="cn">${c.num}</i>${esc(c.title)}</a>`;
|
||||
if (!isCur || !c.sections.length) return row;
|
||||
const sub = c.sections.map(s =>
|
||||
`<a class="toc-a lv3" href="#${s.id}">${esc(s.label)}</a>`).join("");
|
||||
return row + `<div class="subnav current">${sub}</div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function chapnav(c) {
|
||||
return ` <a href="index.html">Nginx 专题</a>\n` +
|
||||
` <span>·</span>\n` +
|
||||
` <span>第 <b class="pos">${c.num}</b> / ${chapters.length} 章</span>`;
|
||||
}
|
||||
|
||||
function pager(c) {
|
||||
const i = chapters.indexOf(c);
|
||||
const a = (ch, cls, k) => ch
|
||||
? ` <a class="${cls}" href="${ch.file}"><span class="k">${k}</span><span class="v">第 ${ch.num} 章 · ${esc(ch.title)}</span></a>`
|
||||
: ` <a class="${cls} disabled"><span class="k">${k}</span><span class="v">没有更多了</span></a>`;
|
||||
return a(chapters[i - 1], "prev", "← 上一章") + "\n" + a(chapters[i + 1], "next", "下一章 →");
|
||||
}
|
||||
|
||||
function foot(c) {
|
||||
return ` Nginx 专题 · 第 ${c.num} 章 ${esc(c.title)}<br>\n` +
|
||||
` <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · <a href="../linux/index.html">Linux 专题</a>`;
|
||||
}
|
||||
|
||||
function kpis() {
|
||||
const wan = (totalChars / 10000).toFixed(1);
|
||||
return [
|
||||
`<div class="kpi"><b>${chapters.length}</b><span>章 · 完整知识体系</span></div>`,
|
||||
`<div class="kpi"><b>${totalSecs}</b><span>个知识点小节</span></div>`,
|
||||
`<div class="kpi"><b>${totalPres}</b><span>段可复制代码</span></div>`,
|
||||
`<div class="kpi"><b>${wan} 万</b><span>字正文</span></div>`
|
||||
].join("\n ");
|
||||
}
|
||||
|
||||
function cards() {
|
||||
return chapters.map(c => {
|
||||
const search = [c.title, c.desc, c.keywords, c.sections.map(s => s.label).join(" ")]
|
||||
.join(" ").toLowerCase();
|
||||
const secs = c.sections.map(s =>
|
||||
`<a href="${c.file}#${s.id}">${esc(s.label)}</a>`).join("");
|
||||
return ` <div class="chapcard" data-search="${esc(search)}">
|
||||
<div class="cc-head">
|
||||
<input type="checkbox" data-ch="${c.num}" aria-label="标记第 ${c.num} 章已读">
|
||||
<span class="cc-no">${c.num}</span>
|
||||
<a class="cc-title" href="${c.file}">${esc(c.title)}</a>
|
||||
<a class="cc-go" href="${c.file}">进入 →</a>
|
||||
</div>
|
||||
<p class="cc-desc">${esc(c.desc)}</p>
|
||||
<details class="cc-secs">
|
||||
<summary>${c.sections.length} 个小节 · 展开看知识点</summary>
|
||||
<div>${secs}</div>
|
||||
</details>
|
||||
</div>`;
|
||||
}).join("\n");
|
||||
}
|
||||
|
||||
/* ---------------------------- 3. 写回 ---------------------------- */
|
||||
const Z = (re, gen, only) => ({ re, gen, only }); // only: "index" | "chapter" | undefined
|
||||
|
||||
const zones = [
|
||||
Z(/<nav id="chapters">[\s\S]*?<\/nav>/, (c, idx) => `<nav id="chapters">${navTree(idx ? 0 : c.num)}</nav>`),
|
||||
Z(/<p class="chapnav">[\s\S]*?<\/p>/, c => `<p class="chapnav">\n${chapnav(c)}\n </p>`, "chapter"),
|
||||
Z(/<!-- AUTO:kpis -->[\s\S]*?<!-- \/AUTO:kpis -->/, () => `<!-- AUTO:kpis -->\n ${kpis()}\n <!-- /AUTO:kpis -->`, "index"),
|
||||
Z(/<!-- AUTO:cards -->[\s\S]*?<!-- \/AUTO:cards -->/, () => `<!-- AUTO:cards -->\n${cards()}\n <!-- /AUTO:cards -->`, "index"),
|
||||
Z(/<nav class="pager">[\s\S]*?<\/nav>/, (c, idx) => idx
|
||||
? `<nav class="pager">\n <a class="next" href="${chapters[0].file}"><span class="k">开始阅读 →</span><span class="v">第 1 章 · ${esc(chapters[0].title)}</span></a>\n </nav>`
|
||||
: `<nav class="pager">\n${pager(c)}\n </nav>`),
|
||||
Z(/<p class="foot">[\s\S]*?<\/p>/, (c, idx) => idx
|
||||
? `<p class="foot">\n Nginx 专题知识库 · 共 ${chapters.length} 章 ${totalSecs} 个小节 · ${totalPres} 段代码<br>\n <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · <a href="../linux/index.html">Linux 专题</a>\n </p>`
|
||||
: `<p class="foot">\n${foot(c)}\n </p>`)
|
||||
];
|
||||
|
||||
let pages = 0;
|
||||
const targets = chapters.map(c => ({ c, file: c.file, idx: false }));
|
||||
if (fs.existsSync(path.join(root, "index.html"))) {
|
||||
targets.push({ c: chapters[0], file: "index.html", idx: true });
|
||||
}
|
||||
|
||||
for (const t of targets) {
|
||||
const p = path.join(root, t.file);
|
||||
let html = fs.readFileSync(p, "utf8");
|
||||
for (const z of zones) {
|
||||
if (z.only === "index" && !t.idx) continue;
|
||||
if (z.only === "chapter" && t.idx) continue;
|
||||
if (!z.re.test(html)) throw new Error(`${t.file}: 缺少占位区块 ${z.re}`);
|
||||
html = html.replace(z.re, z.gen(t.c, t.idx));
|
||||
}
|
||||
fs.writeFileSync(p, html, "utf8");
|
||||
pages++;
|
||||
}
|
||||
|
||||
chapters.forEach(c => console.log(
|
||||
`${c.file.padEnd(20)} 第 ${String(c.num).padStart(2)} 章 · ${String(c.sections.length).padStart(2)} 小节 · ` +
|
||||
`${String(c.pres).padStart(2)} 段代码 · ${String(c.chars).padStart(6)} 字 · ${c.title}`));
|
||||
console.log(`\n共 ${chapters.length} 章 / ${totalSecs} 小节 / ${totalPres} 段代码 / ${(totalChars / 10000).toFixed(1)} 万字,已同步 ${pages} 个页面。`);
|
||||
167
knowledge/nginx/tools/check-chapter.js
Normal file
167
knowledge/nginx/tools/check-chapter.js
Normal file
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Nginx 专题 · 单章自检(写章节时用这个,比全站 check-pages.js 更聚焦)
|
||||
用法:node tools/check-chapter.js 03-config.html
|
||||
node tools/check-chapter.js # 不给参数则检查所有 NN-*.html
|
||||
|
||||
只校验「作者需要负责」的东西,不校验侧栏/上下章/页脚(那些由
|
||||
tools/build-nav.js 在收尾时统一生成,中途为空是正常的):
|
||||
- 模板结构:title / meta description / meta keywords / article / 四个占位块 /
|
||||
doc.css / doc.js / 主题按钮 / 不越界链接
|
||||
- 代码块:data-lang 是否标注且在允许列表内、块内 < 是否转义
|
||||
- 标签配对:div/section/article/aside/nav/main/details/table/ul/ol/li
|
||||
- 章节:h2 有 id、h3 全部有 id 且以 sec-章号- 开头、小节数 3–10
|
||||
- 组件:至少 1 个 .box、至少 1 个表格或卡片组、至少 1 处实战落点
|
||||
- 体量:至少 3 个代码块、正文不少于 2800 字
|
||||
- 链接:跨章链接指向的文件若尚未生成会标为提示(可忽略),存在则校验锚点
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const problems = [];
|
||||
const hints = [];
|
||||
|
||||
const LANGS = ["bash", "shell", "sh", "console", "text", "yaml", "yml", "json", "dockerfile",
|
||||
"go", "javascript", "js", "typescript", "ts", "python", "java", "sql", "nginx", "ini",
|
||||
"toml", "conf", "lua", "powershell", "http", "makefile", "dockerignore", "properties",
|
||||
"xml", "csv", "promql"];
|
||||
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, "");
|
||||
const norm = s => s.replace(/\s+/g, "").length;
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const files = args.length
|
||||
? args
|
||||
: fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
|
||||
|
||||
if (!files.length) {
|
||||
console.error("没有找到章节文件。用法:node tools/check-chapter.js 03-config.html");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/* 已存在章节的 id 索引,用于跨章锚点校验 */
|
||||
const idIndex = new Map();
|
||||
for (const f of fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).concat(["index.html"])) {
|
||||
if (!fs.existsSync(path.join(root, f))) continue;
|
||||
idIndex.set(f, new Set([...fs.readFileSync(path.join(root, f), "utf8")
|
||||
.matchAll(/\sid="([^"]+)"/g)].map(m => m[1])));
|
||||
}
|
||||
|
||||
for (const f of files) {
|
||||
const p = path.join(root, f);
|
||||
if (!fs.existsSync(p)) { problems.push(`${f}: 文件不存在`); continue; }
|
||||
if (!/^\d\d-.*\.html$/.test(f)) { problems.push(`${f}: 文件名必须是 NN-slug.html`); continue; }
|
||||
|
||||
const html = fs.readFileSync(p, "utf8");
|
||||
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
|
||||
const num = parseInt(f.slice(0, 2), 10);
|
||||
const own = [];
|
||||
|
||||
/* ---------------- 结构 ---------------- */
|
||||
if (!new RegExp(`<title>[^<]*第 ${num} 章[^<]*</title>`).test(html)) own.push("title 里应含「第 N 章」");
|
||||
if (!/<article>/.test(html)) own.push("缺少 <article>");
|
||||
if (!html.includes('id="chapters"')) own.push("缺少侧栏 <nav id=\"chapters\">");
|
||||
if (!html.includes('class="chapnav"')) own.push("缺少 <p class=\"chapnav\"></p>");
|
||||
if (!html.includes('class="pager"')) own.push("缺少 <nav class=\"pager\"></nav>");
|
||||
if (!html.includes('class="foot"')) own.push("缺少 <p class=\"foot\"></p>");
|
||||
if (!html.includes('href="assets/doc.css"')) own.push("doc.css 路径不对");
|
||||
if (!html.includes('src="assets/doc.js"')) own.push("doc.js 路径不对");
|
||||
if (!html.includes('id="themeBtn"')) own.push("缺少主题切换按钮");
|
||||
if (!html.includes('href="index.html"')) own.push("缺少返回总目录链接");
|
||||
if (!/class="brand"/.test(html)) own.push("缺少 topbar 品牌区");
|
||||
if (!/<h2 id="ch\d+"><span class="n">\d+<\/span>/.test(html)) own.push("章标题格式应为 <h2 id=\"chN\"><span class=\"n\">N</span>标题</h2>");
|
||||
if (!/class="lead"/.test(html)) own.push("缺少 <div class=\"lead\">");
|
||||
|
||||
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
if (desc.trim().length < 20) own.push(`meta description 太短或缺失(${desc.length} 字)`);
|
||||
const keys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
|
||||
if (keys.trim().length < 6) own.push(`meta keywords 太短或缺失(${keys.length} 字)`);
|
||||
|
||||
if (/href="\.\.\/(?!(docker|linux|sre-learning-path|nginx)\/)/.test(markup)) {
|
||||
own.push("站内链接不应跑出本资料目录(只允许 ../docker/、../linux/、../nginx/、../sre-learning-path/)");
|
||||
}
|
||||
|
||||
/* ---------------- 代码块 ---------------- */
|
||||
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
|
||||
pres.forEach((blk, i) => {
|
||||
if (!/data-lang=/.test(blk)) own.push(`第 ${i + 1} 个 <pre> 未标注 data-lang`);
|
||||
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
|
||||
if (/</.test(body)) own.push(`第 ${i + 1} 个 <pre> 内有未转义的 <(应为 <)`);
|
||||
});
|
||||
for (const m of markup.matchAll(/<pre data-lang="([^"]*)"/g)) {
|
||||
if (!LANGS.includes(m[1])) own.push(`data-lang="${m[1]}" 不在允许列表里(见 SPEC 第 2 节)`);
|
||||
}
|
||||
if (pres.length < 3) own.push(`代码块过少(${pres.length}),至少 3 个`);
|
||||
|
||||
/* ---------------- 标签配对 ---------------- */
|
||||
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
|
||||
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
|
||||
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
|
||||
if (o !== c) own.push(`<${t}> 开合不匹配 ${o}/${c}`);
|
||||
}
|
||||
|
||||
/* ---------------- 组件构成 ---------------- */
|
||||
if (!/class="box (note|tip|warn|danger|ok|case|lab)"/.test(html)) own.push("没有任何 .box 提示框");
|
||||
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) own.push("既没有表格也没有卡片组");
|
||||
if (!/class="box case"|class="box lab"|实战|实际用法/.test(html)) {
|
||||
own.push("缺少「开发/运维实际用法」落点(.box case / .box lab / 标题含实战)");
|
||||
}
|
||||
|
||||
/* ---------------- 小节 ---------------- */
|
||||
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
|
||||
const h3any = (html.match(/<h3[ >]/g) || []).length;
|
||||
if (h3.length !== h3any) own.push(`有 ${h3any - h3.length} 个 h3 未补 id`);
|
||||
if (h3.length < 3) own.push(`小节过少(${h3.length}),至少 3 个`);
|
||||
if (h3.length > 10) own.push(`小节过多(${h3.length}),最多 10 个`);
|
||||
const seen = new Set();
|
||||
const secOrder = [];
|
||||
for (const m of h3) {
|
||||
if (!m[1].startsWith(`sec-${num}-`)) own.push(`小节 id "${m[1]}" 应以 sec-${num}- 开头`);
|
||||
if (seen.has(m[1])) own.push(`小节 id 重复:${m[1]}`);
|
||||
seen.add(m[1]);
|
||||
/* 标题文本必须带「N.M」编号,且与 id 里的序号一致 */
|
||||
const title = stripTags(m[2]).replace(/ /g, " ").trim();
|
||||
const label = title.match(/^(\d+)\.(\d+)\b/);
|
||||
const idSeq = m[1].slice(`sec-${num}-`.length);
|
||||
if (!label) own.push(`小节标题缺少「${num}.M」编号:${title.slice(0, 30)}`);
|
||||
else {
|
||||
if (label[1] !== String(num)) own.push(`小节标题编号与章号不符:${title.slice(0, 30)}`);
|
||||
if (label[2] !== idSeq) own.push(`小节标题编号 ${label[1]}.${label[2]} 与 id ${m[1]} 不一致`);
|
||||
secOrder.push(parseInt(label[2], 10));
|
||||
}
|
||||
}
|
||||
for (let i = 1; i < secOrder.length; i++) {
|
||||
if (secOrder[i] !== secOrder[i - 1] + 1) own.push(`小节编号不连续:…${secOrder[i - 1]} → ${secOrder[i]}`);
|
||||
}
|
||||
|
||||
/* ---------------- 体量 ---------------- */
|
||||
const body = norm(stripTags(markup.replace(/<pre[\s\S]*?<\/pre>/g, " ")));
|
||||
if (body < 2800) own.push(`正文过短(约 ${body} 字,不含代码),至少要 2800 字`);
|
||||
|
||||
/* ---------------- 链接与锚点 ---------------- */
|
||||
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map(m => m[1]))) {
|
||||
const [file, hash] = l.split("#");
|
||||
const target = path.join(root, file || f);
|
||||
if (file && !fs.existsSync(target)) { hints.push(`${f}: 目标章节尚未生成 → ${l}`); continue; }
|
||||
const key = path.basename(file || f);
|
||||
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) own.push(`锚点不存在:${l}`);
|
||||
}
|
||||
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map(m => m[1]))) {
|
||||
if (idIndex.has(f) && !idIndex.get(f).has(l)) own.push(`页内锚点不存在:#${l}`);
|
||||
}
|
||||
|
||||
if (own.length) problems.push(...own.map(x => `${f}: ${x}`));
|
||||
console.log(`${f.padEnd(20)} ${String(h3.length).padStart(2)} 小节 · ${String(pres.length).padStart(2)} 段代码 · ${body} 字正文 · ${own.length ? "✗ " + own.length + " 个问题" : "✓ 通过"}`);
|
||||
}
|
||||
|
||||
if (hints.length) {
|
||||
console.log(`\n提示(并行写作期间正常,可忽略):`);
|
||||
hints.slice(0, 12).forEach(x => console.log(" - " + x));
|
||||
}
|
||||
if (problems.length) {
|
||||
console.error(`\n发现 ${problems.length} 个问题:`);
|
||||
problems.forEach(x => console.error(" - " + x));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\nOK ${files.length} 个章节文件全部通过单章自检。`);
|
||||
188
knowledge/nginx/tools/check-pages.js
Normal file
188
knowledge/nginx/tools/check-pages.js
Normal file
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Nginx 专题 · 页面自检
|
||||
用法:node tools/check-pages.js [站点根目录,默认本文件的上一级]
|
||||
|
||||
检查项:
|
||||
- 结构:title / article / #chapters / doc.css / doc.js / chapnav / pager / foot
|
||||
- 代码块:是否标注 data-lang、块内 < 是否转义
|
||||
- 标签配对:div/section/article/aside/nav/main/details/table/ul/ol/li
|
||||
- 链接:站内文件是否存在、锚点是否真实可达
|
||||
- 章节:h2 有 id、h3 全部有 id、小节 id 前缀与章号一致
|
||||
- 目录树:每个页面都列出全部章节,当前章展开小节且数量与正文一致
|
||||
- 体量:章节正文过短会提示(防止只写了标题)
|
||||
- 静态资源:doc.css/doc.js 存在、样式表花括号配平、品牌色变量已定义
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = process.argv[2] || path.resolve(__dirname, "..");
|
||||
const problems = [];
|
||||
const info = [];
|
||||
|
||||
const must = (c, m) => { if (!c) problems.push(m); };
|
||||
const read = p => fs.readFileSync(p, "utf8");
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, "");
|
||||
const norm = s => s.replace(/\s+/g, "").length;
|
||||
|
||||
const chapterFiles = fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
|
||||
must(chapterFiles.length >= 5, "章节页数量异常:" + chapterFiles.length);
|
||||
const pages = chapterFiles.concat(fs.existsSync(path.join(root, "index.html")) ? ["index.html"] : []);
|
||||
const totalChapters = chapterFiles.length;
|
||||
|
||||
/* id 索引,供锚点校验 */
|
||||
const idIndex = new Map();
|
||||
for (const f of pages) {
|
||||
const html = read(path.join(root, f));
|
||||
idIndex.set(f, new Set([...html.matchAll(/\sid="([^"]+)"/g)].map(m => m[1])));
|
||||
}
|
||||
|
||||
for (const f of pages) {
|
||||
const html = read(path.join(root, f));
|
||||
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
|
||||
const isIndex = f === "index.html";
|
||||
|
||||
must(/<title>[^<]+<\/title>/.test(html), `${f}: 缺少 title`);
|
||||
must(html.includes("<article>"), `${f}: 缺少 <article>`);
|
||||
must(html.includes('id="chapters"'), `${f}: 缺少侧栏 #chapters`);
|
||||
must(html.includes('href="assets/doc.css"'), `${f}: doc.css 路径不对`);
|
||||
must(html.includes('src="assets/doc.js"'), `${f}: doc.js 路径不对`);
|
||||
must(html.includes('id="themeBtn"'), `${f}: 缺少主题切换按钮`);
|
||||
must(!/href="\.\.\//.test(markup.replace(/href="\.\.\/(sre-learning-path|docker|linux|nginx)\/[^"]*"/g, "")),
|
||||
`${f}: 站内链接不应跑出本资料目录(只允许指向其它知识站点的页面)`);
|
||||
|
||||
/* 代码块 */
|
||||
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
|
||||
pres.forEach((blk, i) => {
|
||||
if (!/data-lang=/.test(blk)) problems.push(`${f}: 第 ${i + 1} 个 <pre> 未标注 data-lang`);
|
||||
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
|
||||
if (/</.test(body)) problems.push(`${f}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
|
||||
});
|
||||
|
||||
/* 标签配对 */
|
||||
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
|
||||
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
|
||||
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
|
||||
if (o !== c) problems.push(`${f}: <${t}> 开合不匹配 ${o}/${c}`);
|
||||
}
|
||||
|
||||
/* 链接与锚点 */
|
||||
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map(m => m[1]))) {
|
||||
const [file, hash] = l.split("#");
|
||||
const target = path.resolve(root, file || f);
|
||||
if (file && !fs.existsSync(target)) { problems.push(`${f}: 死链 ${l}`); continue; }
|
||||
const key = file ? path.basename(file) : f;
|
||||
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) problems.push(`${f}: 锚点不存在 ${l}`);
|
||||
}
|
||||
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map(m => m[1]))) {
|
||||
if (!idIndex.get(f).has(l)) problems.push(`${f}: 页内锚点不存在 #${l}`);
|
||||
}
|
||||
|
||||
if (!isIndex) {
|
||||
const num = parseInt(f.slice(0, 2), 10);
|
||||
const h2 = html.match(/<h2 id="([^"]+)">([\s\S]*?)<\/h2>/);
|
||||
|
||||
/* 内容体量与组件构成 */
|
||||
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
if (desc.trim().length < 20) problems.push(`${f}: meta description 太短或缺失(${desc.length} 字)`);
|
||||
if (!/class="box /.test(html)) problems.push(`${f}: 没有任何 .box 提示框`);
|
||||
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) {
|
||||
problems.push(`${f}: 既没有表格也没有卡片组`);
|
||||
}
|
||||
if (pres.length < 2) problems.push(`${f}: 代码块过少(${pres.length}),至少 2 个`);
|
||||
const LANGS = ["bash", "shell", "sh", "console", "text", "yaml", "yml", "json", "dockerfile",
|
||||
"go", "javascript", "js", "typescript", "ts", "python", "java", "sql", "nginx", "ini",
|
||||
"toml", "conf", "lua", "powershell", "http", "makefile", "dockerignore", "properties", "xml", "csv", "promql"];
|
||||
for (const m of markup.matchAll(/<pre data-lang="([^"]*)"/g)) {
|
||||
if (!LANGS.includes(m[1])) problems.push(`${f}: data-lang="${m[1]}" 不在允许列表里`);
|
||||
}
|
||||
must(!!h2, `${f}: 缺少 h2 章节标题`);
|
||||
must(html.includes('class="chapnav"'), `${f}: 缺少章节定位条 .chapnav`);
|
||||
must(html.includes('class="pager"'), `${f}: 缺少上一/下一章 .pager`);
|
||||
must(html.includes('class="foot"'), `${f}: 缺少页脚 .foot`);
|
||||
must(html.includes('href="index.html"'), `${f}: 缺少返回总目录链接`);
|
||||
must(/class="toc-a active"[^>]*aria-current="page"/.test(html), `${f}: 当前章未标记 active`);
|
||||
|
||||
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
|
||||
const h3any = (html.match(/<h3[ >]/g) || []).length;
|
||||
must(h3.length === h3any, `${f}: 有 h3 未补 id(${h3.length}/${h3any})`);
|
||||
must(h3.length >= 3, `${f}: 小节过少(${h3.length}),至少 3 个`);
|
||||
for (const m of h3) {
|
||||
if (!m[1].startsWith(`sec-${num}-`)) problems.push(`${f}: 小节 id "${m[1]}" 应以 sec-${num}- 开头`);
|
||||
}
|
||||
/* 上下章导航必须是「上一章 / 下一章」,页脚必须是本章标题 */
|
||||
const pager = html.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
|
||||
must(!!pager && /上一章|下一章/.test(pager[1]), `${f}: .pager 不是章节页的上一/下一章导航`);
|
||||
must(!!pager && !/开始阅读/.test(pager[1]), `${f}: .pager 误用了目录页的「开始阅读」`);
|
||||
must(/class="foot">\s*Nginx 专题 · 第 \d+ 章/.test(html.replace(/\n/g, "")),
|
||||
`${f}: 页脚不是本章标题(可能是目录页页脚)`);
|
||||
|
||||
/* 目录树里当前章的小节数量要与正文一致 */
|
||||
const sub = html.match(/<div class="subnav current">([\s\S]*?)<\/div>/);
|
||||
must(!!sub, `${f}: 侧栏缺少当前章小节`);
|
||||
if (sub) {
|
||||
const n = (sub[1].match(/class="toc-a lv3"/g) || []).length;
|
||||
must(n === h3.length, `${f}: 侧栏小节数 ${n} ≠ 正文 h3 数 ${h3.length}`);
|
||||
}
|
||||
const body = norm(stripTags(markup));
|
||||
if (body < 2200) problems.push(`${f}: 正文过短(约 ${body} 字),内容需要补充`);
|
||||
}
|
||||
|
||||
/* 目录树必须列出全部章节 */
|
||||
const nav = html.match(/<nav id="chapters">([\s\S]*?)<\/nav>/);
|
||||
must(!!nav, `${f}: 缺少 #chapters 目录树`);
|
||||
if (isIndex) {
|
||||
const pg = html.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
|
||||
must(!!pg && /开始阅读/.test(pg[1]), "index.html: .pager 缺少「开始阅读」入口");
|
||||
must(!!pg && !/上一章|下一章/.test(pg[1]), "index.html: .pager 误用了章节页的上一/下一章");
|
||||
must(/class="foot">\s*Nginx 专题知识库/.test(html.replace(/\n/g, "")), "index.html: 页脚不是目录页页脚");
|
||||
}
|
||||
if (nav) {
|
||||
const rows = (nav[1].match(/class="toc-a( active)?"/g) || []).length;
|
||||
must(rows === totalChapters, `${f}: 目录树章节数 ${rows} ≠ ${totalChapters}`);
|
||||
for (const cf of chapterFiles) {
|
||||
if (cf === f) continue;
|
||||
must(nav[1].includes(`href="${cf}"`), `${f}: 目录树缺少章节 ${cf}`);
|
||||
}
|
||||
if (isIndex) must(!/class="subnav/.test(nav[1]), "index.html: 目录页不应展开任何章的小节");
|
||||
}
|
||||
|
||||
info.push(`${f.padEnd(24)} ~${norm(stripTags(markup))} 字 · 代码块 ${pres.length}`);
|
||||
}
|
||||
|
||||
info.sort();
|
||||
|
||||
/* ---------------- 静态资源完整性 ----------------
|
||||
doc.css 是整站全局生效的:一处花括号失衡,后面的声明就会整段泄漏到全局,
|
||||
排版会当场崩掉(真实事故:删重复 @media print 时留下了它的声明体,导致
|
||||
body 变白底小字号、.layout 失去 flex、article 丢掉内边距)。
|
||||
页面级检查看不出这种问题,所以这里单独守住样式表本身。 */
|
||||
for (const asset of ["assets/doc.css", "assets/doc.js"]) {
|
||||
must(fs.existsSync(path.join(root, asset)), `缺少静态资源 ${asset}`);
|
||||
}
|
||||
const cssFile = path.join(root, "assets/doc.css");
|
||||
if (fs.existsSync(cssFile)) {
|
||||
const css = read(cssFile).replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
let depth = 0, extra = 0, line = 1, firstExtra = 0;
|
||||
for (const ch of css) {
|
||||
if (ch === "\n") { line++; continue; }
|
||||
if (ch === "{") depth++;
|
||||
else if (ch === "}") {
|
||||
depth--;
|
||||
if (depth < 0) { extra++; if (!firstExtra) firstExtra = line; }
|
||||
}
|
||||
}
|
||||
must(depth === 0 && extra === 0,
|
||||
`assets/doc.css: 花括号不配平(` +
|
||||
(extra ? `第 ${firstExtra} 行附近多出 ${extra} 个 }` : `还有 ${depth} 个 { 未闭合`) +
|
||||
`)——声明会泄漏到全局,页面排版会崩`);
|
||||
must(/--brand\s*:/.test(css), "assets/doc.css: 未定义 --brand 品牌色变量(可能复制了别站的样式表)");
|
||||
}
|
||||
|
||||
console.log(info.join("\n"));
|
||||
if (problems.length) {
|
||||
console.error(`\n发现 ${problems.length} 个问题:`);
|
||||
problems.slice(0, 60).forEach(x => console.error(" - " + x));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\nOK 全部校验通过(${chapterFiles.length} 章 + 目录页,共 ${pages.length} 个页面)`);
|
||||
359
knowledge/nginx/tools/verify-behavior.js
Normal file
359
knowledge/nginx/tools/verify-behavior.js
Normal file
@@ -0,0 +1,359 @@
|
||||
#!/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": "<!doctype html><title>spa</title>SPA-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) {}
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user