Nginx 静态站点与 location 匹配:优先级、alias、缓存头与 gzip

这是《Nginx 从入门到精通》系列的第 4 篇(全系列 15 篇 + 4 个实战项目)。目标:把 location 匹配规则变成肌肉记忆------能独立写出「静态长缓存 + HTML 短缓存 + gzip + 自定义错误页 + SPA 回退」的 server 块,并说清其中每一个响应头是怎么来的。

前置 :第 3 篇(配置语法与上下文)的继承规则与 nginx -T 手法、第 2 篇(安装与目录结构)里 mime.types 的位置;实验复用 lab/00-env。 本文所有响应头与状态码均为 nginx 1.30.6(stable)实测,文末附 5 道自测与延伸阅读。


1. 先跑起来(5 分钟实验)

一条 HEAD 请求就能看清 location、alias、expires、Range 四件事:

bash 复制代码
cd nginx/lab/00-env
docker compose up -d
curl -sI localhost:8080/static/index.html \
  | sed -n '1p;/Cache-Control/Ip;/Expires/Ip;/ETag/Ip;/Accept-Ranges/Ip'

预期输出(关键行,时间戳随文件变化):

text 复制代码
HTTP/1.1 200 OK
ETag: "6ae94fec-290"
Expires: Tue, 10 Nov 2026 04:19:44 GMT
Cache-Control: max-age=604800
Cache-Control: public
Accept-Ranges: bytes

三件事立刻可读:

观察 结论
/static/index.html 出的是 /usr/share/nginx/html/index.html location /static/ 里写的是 alias /usr/share/nginx/html/;,匹配到的前缀被替换,不是拼接
Expires 与 Cache-Control: max-age=604800 同时出现 expires 7d 一条指令发两个头(7 天 = 604800 秒),这是 HTTP/1.0 与 1.1 两套语义的兼容产物
末尾还有一条 Cache-Control: public 同一个 location 的 add_header 追加的,两条 Cache-Control 并存是 lab 故意留的演示坑(见坑 5)

再验一次条件请求------这才是缓存的真实收益点,而不是「省了带宽」这种空话:

bash 复制代码
ET=$(curl -sI localhost:8080/static/index.html | awk '/^ETag:/{print $2}' | tr -d '\r')
curl -s -o /dev/null -w '%{http_code}\n' -H "If-None-Match: $ET" localhost:8080/static/index.html
# 304  ← 文件没变,响应体 0 字节,但请求仍然到达了服务器

2. 核心概念

2.1 location 是一条判定链,不是一排平级的 if

顺序 修饰符 语义 典型用途 命中之后
1 = 整条 URI 完全相等 /healthz、/nginx_status 立即定案,正则全部不参与
2 ^~ 最长前缀,且放弃正则 静态资源目录、不许被正则抢的路径 用该 location,跳过所有 ~/~*
3 ~ / ~* 正则(~* 忽略大小写),按书写顺序 扩展名分发、伪静态、下载目录 第一个命中的正则胜出
4 普通前缀 最长匹配,但还要让正则过一遍 location /、目录映射 若有正则能命中,改用正则
5 @name 命名 location,只供内部跳转 error_page、try_files 兜底 外部请求永远到不了它

判定流程(背这张图比背文字快):

text 复制代码
URI 归一化(merge_slashes 合并 //、解码 %XX、处理 ../)
  ├─ 有完全相等的 = ? ───── 是 → 用它,结束
  ├─ 记下最长前缀 P;P 带 ^~ ? → 用 P,结束(正则不看了)
  ├─ 按书写顺序试 ~ / ~* ── 第一个命中 → 用它,结束
  └─ 都不命中 ───────────── 用 P(最终兜底是 location /)

同一组 5 条 location 的实测命中表(实验 1 可复现):

请求 命中 为什么
/a = /a 精确匹配,优先级最高
/a/b location / = 是全等比较,而这份配置没有 /a 的前缀版
/a.php ~ \.php$ 正则优先于普通前缀
/static/a.php ~ \.php$ 普通前缀的命中会被能命中的正则改写
/static/a.txt location /static/ 没有正则命中 txt,回落最长前缀
/static/img/logo.png ^~ /static/img/ ^~ 命中后彻底不看正则
/static/img/x.php ^~ /static/img/ 同上,正则被压制
//a = /a merge_slashes(默认 on)先把 // 归一

一句话记住顺序:= > ^~ 最长前缀 > 正则(先写的先赢)> 普通前缀最长匹配(可被正则改写)。写错这一层不报错、只是走错分支,所以本章的每个实验都看你命中了哪一条。

2.2 root 拼接,alias 替换------差一个字符就错位

写法 请求 实际磁盘路径 规则
root /data/www; /a/b /data/www/a/b root 拼的是完整 URI
location /static/ { alias /d/st/; } /static/a.png /d/st/a.png alias 替换匹配到的那段前缀
location /static/ { alias /d/st; } /static/a.png /d/sta.png 少结尾斜杠 → 拼串错位 → 404
location ~ ^/d/(.+)$ { alias /f/$1; } /d/a.pdf /f/a.pdf 正则 location 的 alias 必须写捕获

为什么这样设计:root 适合「一个 URI 空间 = 一棵目录树」的常规站点;alias 适合「URI 与磁盘目录不同构」的场景(下载目录、CDN 目录、多站点共享文件)。代价是 alias 本质做字符串替换,斜杠与捕获写错就错位,而错位出的路径可能落到别的目录------坑 1、3 与实验 3 的「穿越」都源于此。

2.3 try_files 的三种收尾

写法 语义 什么时候用 坑
try_files $uri $uri/ =404; 文件 → 目录 → 404 纯静态站 少写 = 会被当成根目录下名为 404 的文件
try_files $uri $uri/ /index.html; 文件 → 目录 → 内部跳转,URL 不变 SPA / history 路由 兜底跳回自身 → 500 循环
try_files $uri @fallback; 交给命名 location 动态兜底、多后端兜底 @name 只能在同一个 server 内

末项若既不是 =code、也不以 / 开头,nginx 会把它当相对 root 的文件名 去 open();带斜杠的 /index.html 才走内部跳转。这条差异是坑 2 的依据。

2.4 缓存头、条件请求与 Range

指令 发出的响应头 默认值 什么时候必须改
expires 30d Expires + Cache-Control: max-age=2592000 off 带 hash 的资源要 1y;HTML 要短或不缓存
add_header Cache-Control ... 再追加一条 Cache-Control 无 想加 public, immutable 时别与 expires 并存
etag on ETag("长度-修改时间" 的十六进制) on(≥1.3.3) 多机时间戳不一致时关掉,只信 Last-Modified
if_modified_since exact 决定 If-Modified-Since 的 304 判定 exact 一般不动;设 off 会让 304 彻底失效
max_ranges 配合 Accept-Ranges: bytes 与 206 不限制 公网下载站设 1,防 Range 放大攻击

实测语义:Range: bytes=0-99 → 206 Partial Content + Content-Range: bytes 0-99/100000;If-None-Match 命中 → 304;If-Range 带过期 ETag → 直接 200 回整份文件(续传前缀已不可信)。

2.5 压缩与大文件

项 默认值 要点
default_type text/plain lab 设为 application/octet-stream;未知扩展名落到它,浏览器直接下载而不是显示
charset / source_charset 各自 off 只对 charset_types 里的类型补 ; charset=utf-8(application/json 不在默认列表);源站 GBK 才配 source_charset,且 UTF-8 ↔ GBK 没有内置 charset_map,只写两行会启动失败
gzip off text/html 永远压缩,其它类型必须进 gzip_types
gzip_comp_level / gzip_min_length 1 / 20 字节 6 是性价比拐点(9 只省几个字节却多烧 CPU);最小长度配到 1k 量级,太小会越压越大
gzip_vary off 必须 on:缺 Vary: Accept-Encoding 时 CDN 会把压缩版发给不支持的客户端
gzip_static off 直发预生成的 .gz,几乎不耗 CPU;要自己预先压好
brotli 第三方模块 官方镜像不含 ,需自编译 ngx_brotli;不可用时用 gzip 兜底

大文件四件套:sendfile on 让内核把文件直接送进 socket(零拷贝);tcp_nopush on 攒满首包再发,减少小包;sendfile_max_chunk 限制单次 sendfile 块大小,防一个大文件长时间霸占 worker(默认 2m,≥1.21.4;更早版本 0 表示不限);directio 8m 让超过 8MB 的文件绕过 page cache,避免一次下载把内存打满。


3. 指令详解

指令 默认值 上下文 说明与坑
location --- server, location 五种形态对应 2.1 判定链;= 必须完全相等,^~ 只能配前缀
root html http, server, location, if 拼完整 URI ;改 root 常忘确认 index 指向的文件还在
alias --- location 只能写在 location 内;替换匹配前缀,结尾斜杠与 location 对齐;正则里必须带捕获
try_files --- server, location 末项是 =code、URI 或文件名;与 alias 同用会失效(坑 4)
index index.html http, server, location 可写多个按序尝试;与 try_files $uri/ 的目录查找是两条不同路径
autoindex off http, server, location 生产默认关(目录列表 = 信息泄露);只在受控目录开,配 autoindex_localtime
error_page --- http, server, location, if 是内部跳转;=200 可改写状态码,单独 = 表示保留原状态码
internal off location 只能被内部跳转命中,直接访问返回 404------错误页、状态页必备
gzip / gzip_types / gzip_vary off / text/html / off http, server, location, if 三者要一起配;只开 gzip 不开 vary,等于给 CDN 埋雷
gzip_static off http, server, location, if 需要同名 .gz,优先生效于 gzip,CPU 几乎为零
expires off http, server, location, if 支持 1h、30d、max、epoch、@15h30m;与 add_header Cache-Control 并存会产生两个头
add_header --- http, server, location, if 子级出现即覆盖父级 ,不是累加;公共头要 include 片段或在每个 location 重复
etag on(≥1.3.3) http, server, location 关掉只留 Last-Modified;CDN 对 ETag 更敏感
sendfile / aio / directio 各自 off http, server, location aio threads 需 --with-threads(官方镜像已编译);directio 的粒度是文件大小

4. 完整配置示例

4.1 主配置 nginx/nginx.conf:替换 gzip 那几行

nginx 复制代码
charset utf-8;
merge_slashes on;                       # //a 归一成 /a
sendfile on;  sendfile_max_chunk 1m;  tcp_nopush on;    # 静态零拷贝三件套
gzip on;  gzip_comp_level 6;  gzip_min_length 1024;  gzip_vary on;
gzip_types text/plain text/css application/javascript application/json
           application/xml image/svg+xml;

4.2 站点配置 nginx/conf.d/default.conf

nginx 复制代码
server {
    listen 80;
    server_name _;
    root  /usr/share/nginx/html;
    index index.html;
    # ① 错误页统一入口;页面本身必须 internal,否则外人能直接看
    error_page 404 /404.html;
    error_page 403 /403.html;
    error_page 500 502 503 504 /50x.html;
    location = /404.html { internal; }
    location = /403.html { internal; }
    location = /50x.html { internal; }
    # ② ^~ 最长前缀:图片走 alias + 30 天强缓存,正则不许抢
    location ^~ /static/img/ {
        alias /usr/share/nginx/html/img/;
        expires 30d;
        access_log off;
    }
    # ③ 正则 location:alias 必须带捕获,否则整个目录被当成一个文件
    location ~ ^/download/(.+)$ { alias /usr/share/nginx/html/files/$1; }
    # ④ 普通前缀:css/js 等;没有 ^~,所以正则可以抢
    location /static/ {
        alias /usr/share/nginx/html/;
        expires 7d;
        add_header Cache-Control "public";   # 与 expires 并存 → 两条 Cache-Control(坑 5)
    }
    # ⑤ 目录列表:只在受控目录开,且必须精确匹配
    location = /list/ {
        alias /usr/share/nginx/html/img/;
        autoindex on;  autoindex_exact_size off;  autoindex_localtime on;
    }
    # ⑥ 大文件下载:directio 绕 page cache + aio threads + 大输出缓冲
    location /files/ {
        alias /usr/share/nginx/html/files/;
        directio 8m;  aio threads;  output_buffers 4 256k;  sendfile_max_chunk 512k;
    }
    # ⑦ 健康检查、状态页保持 lab 原样
    location = /healthz    { access_log off; return 200 "gateway ok\n"; }
    location /nginx_status { stub_status;  allow 127.0.0.1;  deny all; }
    # ⑧ 反向代理:第 5 篇主战场;注意 /api/ 的 proxy_pass 带 URI 才是前缀替换
    location /slow/ {
        proxy_pass http://app_pool;
        proxy_read_timeout 5s;
    }
    location /api/ {
        proxy_pass http://app_pool/;
        proxy_connect_timeout 2s;
        proxy_set_header Host $host;            proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  proxy_set_header X-Forwarded-Proto $scheme;
    }
    # ⑨ 兜底:SPA 回退,必须最后写
    location / {
        try_files $uri $uri/ /index.html;
    }
}

4.3 相对 lab/00-env 改了哪几行

# 文件 改动 本章用途
① nginx.conf 新增 charset utf-8、merge_slashes on、sendfile_max_chunk 1m、tcp_nopush on、gzip_comp_level 6、gzip_min_length 1024、gzip_vary on;gzip_types 由 4 类扩到 7 类 实验 5
② default.conf 3 条 error_page + 3 个 internal location 实验 4
③ default.conf 新增 ^~ /static/img/、~ ^/download/(.+)$、= /list/、/files/ 四段 实验 3、5
④ default.conf /api/、/slow/、/healthz、/nginx_status、location / 与 lab 语义完全一致 基线不变

校验与生效(漏 -c 等于没校验):

bash 复制代码
cd nginx/lab/00-env
docker compose exec -T gateway nginx -t -c /etc/nginx/lab/nginx.conf \
  && docker compose exec -T gateway nginx -s reload
docker compose exec -T gateway curl -s localhost/healthz

预期最后一行:gateway ok。


5. 必做实验

实验 1:5 条 location 的优先级矩阵

把 nginx/conf.d/default.conf 临时替换成下面这份(做完改回第 4 节):

nginx 复制代码
server {
    listen 80;  server_name _;  root /usr/share/nginx/html;  index index.html;
    location = /a            { add_header X-Loc "A-exact"  always; return 200 "A exact\n"; }
    location ^~ /static/img/ { add_header X-Loc "B-caret"  always; return 200 "B caret\n"; }
    location ~ \.php$        { add_header X-Loc "C-regex"  always; return 200 "C regex php\n"; }
    location /static/        { add_header X-Loc "D-prefix" always; return 200 "D prefix\n"; }
    location /               { add_header X-Loc "E-root"   always; return 200 "E root\n"; }
}
bash 复制代码
docker compose exec -T gateway nginx -t -c /etc/nginx/lab/nginx.conf \
  && docker compose exec -T gateway nginx -s reload
for u in /a /a/b /a.php /static/a.php /static/a.txt /static/img/logo.png /static/img/x.php //a; do
  printf '%-24s -> ' "$u"; docker compose exec -T gateway curl -s "localhost$u" | tr -d '\n'; echo
done

预期(与 2.1 的命中表逐行对应):

text 复制代码
/a                       -> A exact
/a/b                     -> E root
/a.php                   -> C regex php
/static/a.php            -> C regex php
/static/a.txt            -> D prefix
/static/img/logo.png     -> B caret
/static/img/x.php        -> B caret
//a                      -> A exact

为什么:= 只在全等时命中,所以 /a/b 落到兜底;/static/a.php 的最长前缀是普通前缀 /static/,但正则能命中,正则改写前缀结果 ;/static/img/x.php 的最长前缀带 ^~,命中后 nginx 直接终止正则阶段;//a 先被 merge_slashes 归一成 /a 再进判定链。

实验 2:SPA 回退,且 /api 不被吞

改回第 4 节配置并 reload,然后:

bash 复制代码
docker compose exec -T gateway curl -s -o /dev/null -w 'spa   %{http_code}\n' localhost/app/deep/route
docker compose exec -T gateway curl -s -o /dev/null -w 'typo  %{http_code}\n' localhost/no-such-page
docker compose exec -T gateway curl -s -o /dev/null -w 'api   %{http_code}\n' localhost/api/json
docker compose exec -T gateway curl -s localhost/api/json | grep -o '"app": "[^"]*"' | head -1

预期:

text 复制代码
spa   200
typo  200
api   200
"app": "app1"

为什么:/app/deep/route 三个候选都不存在,try_files 落到 /index.html,内部跳转后 URL 不变;/api/json 被更长前缀 location /api/ 先命中,proxy_pass http://app_pool/ 去掉 /api 前缀打给上游(/api/json → /json);typo 200 是本篇最贵的坑------SPA 兜底把真 404 也变成 200,处理办法见坑 8。

实验 3:alias 的三种写法与一次目录穿越

bash 复制代码
mkdir -p nginx/static/files nginx/static/img
printf 'pdf-bytes\n' > nginx/static/files/report.pdf
printf 'img\n'       > nginx/static/img/logo.png
docker compose exec -T gateway curl -s -w ' <- %{http_code}\n' localhost/download/report.pdf   # 正则 alias 捕获
docker compose exec -T gateway curl -s -o /dev/null -w 'img  %{http_code}\n' localhost/static/img/logo.png
docker compose exec -T gateway curl -s -o /dev/null -w 'html %{http_code}\n' localhost/static/index.html

预期:pdf-bytes <- 200、img 200、html 200(三种 alias 写法各命中一条)。

接着做两步破坏性验证。先把 4.2 里 /static/ 的 alias /usr/share/nginx/html/; 结尾斜杠删掉并 reload:

bash 复制代码
docker compose exec -T gateway curl -s -o /dev/null -w 'alias 少斜杠 %{http_code}\n' localhost/static/index.html
docker exec lab-gateway tail -2 /var/log/nginx/lab_error.log

预期 404,日志里是 open() "/usr/share/nginx/htmlindex.html" failed------两段路径粘在一起了。复原后加一条 location /img-trav { alias /usr/share/nginx/html/img/; },触发穿越:

bash 复制代码
docker compose exec -T gateway curl -s -o /dev/null -w '穿越 %{http_code}\n' 'localhost/img-trav../index.html'

预期 200:img-trav.. 是一个字面目录名 (中间没有 /,不参与 .. 归一),location 前缀照样命中,alias 拼出 /usr/share/nginx/html/img/../index.html,越出了 /img/。修复原则见第 10 篇:alias 结尾与 location 对齐、不在配置里拼用户可控路径、必要时 disable_symlinks 加最小权限挂载。

实验 4:自定义错误页 + internal 防护

bash 复制代码
mkdir -p nginx/static/emptydir
printf '<h1>custom 403</h1>\n' > nginx/static/403.html
printf '<h1>custom 404</h1>\n' > nginx/static/404.html
docker compose exec -T gateway curl -s -D- localhost/emptydir/ | sed -n '1p;$p'
docker compose exec -T gateway curl -s -o /dev/null -w 'direct 404.html  %{http_code}\n' localhost/404.html
docker compose exec -T gateway curl -s -o /dev/null -w 'direct 50x.html  %{http_code}\n' localhost/50x.html
docker compose stop app1 app2 app3
docker compose exec -T gateway curl -s -D- localhost/api/json | sed -n '1p;$p'
docker compose start app1 app2 app3

预期:

text 复制代码
HTTP/1.1 403 Forbidden
<h1>custom 403</h1>
direct 404.html  404
direct 50x.html  404
HTTP/1.1 502 Bad Gateway
<h1>50x</h1>

为什么:目录存在、没有 index、autoindex 又关着 → 403,被 error_page 403 /403.html 接走(错误页里不要暴露 nginx 版本);internal 让 /404.html 只能被内部跳转拿到,外部直取是 404;三个后端全停 → 502,同样被自己的 50x 页接住(50x.html 由官方镜像自带)。502 的成因链在第 5 篇,从日志定位在第 9 篇。

实验 5:缓存头、304、Range、gzip 一次看完

bash 复制代码
head -c 100000 /dev/urandom > nginx/static/files/big.bin
yes '<p>hello nginx</p>' | head -200 > nginx/static/big.css        # 3.2KB,够过 gzip_min_length
docker compose exec -T gateway curl -sI localhost/static/img/logo.png | sed -n '1p;/Cache-Control/Ip;/Expires/Ip;/ETag/Ip'
ET=$(docker compose exec -T gateway curl -sI localhost/static/img/logo.png | awk '/^ETag:/{print $2}' | tr -d '\r')
docker compose exec -T gateway curl -s -o /dev/null -w 'If-None-Match %{http_code}\n' -H "If-None-Match: $ET" localhost/static/img/logo.png
docker compose exec -T gateway curl -s -D- -o /dev/null -H 'Range: bytes=0-99' localhost/files/big.bin | sed -n '1p;/Content-Range/p'
docker compose exec -T gateway curl -sI -H 'Accept-Encoding: gzip' localhost/static/big.css | grep -i 'content-encoding\|vary'

预期:

text 复制代码
HTTP/1.1 200 OK
Cache-Control: max-age=2592000
Expires: ...
ETag: "..."
If-None-Match 304
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-99/100000
Content-Encoding: gzip
Vary: Accept-Encoding

为什么:expires 30d 只发 Cache-Control: max-age=2592000(这个 location 没写 add_header Cache-Control);304 来自 ETag 精确匹配;Range 命中是 206 且带 Content-Range;Vary: Accept-Encoding 只有 gzip_vary on 才有------lab 原配置缺这行,改前改后各打一次就能看到差别。去掉 -H 'Accept-Encoding: gzip' 后 Content-Encoding 消失但 Vary 仍在,这是「按编码分桶」的正确行为;小于 gzip_min_length 的文件(如 656 字节的 index.html)一律不压。最后 gzip -k nginx/static/big.css 并临时打开 gzip_static on,Content-Encoding 会由预压的 .gz 直接给出,省掉压缩 CPU。


6. 验收自测(5 题)

Q1. 只给 5 条 location(= /a、^~ /static/img/、~* \.png$、/static/、/),请求 /static/img/a.png、/static/a.png、/a、/a.png 各命中哪条?

答案要点:/static/img/a.png → ^~ /static/img/(最长前缀带 ^~,命中后不再试正则);/static/a.png → ~* \.png$(最长前缀是普通前缀 /static/,但正则能命中,正则胜出);/a → = /a(全等,优先级最高);/a.png → ~* \.png$(= 是全等比较,落到最长前缀 / 后再看正则)。口述口径:= > ^~ 最长前缀 > 正则(先写先赢)> 普通前缀最长匹配(可被正则改写)。

Q2. location /static/ { alias /data/static; } 为什么访问 /static/a.png 会 404?用 root 该怎么写?

答案要点:alias 做的是替换匹配前缀 ------/static/ 换成 /data/static,剩下的 a.png 直接接上,得到 /data/statica.png,不存在 → 404(错误日志里是 open() "/data/statica.png" failed)。结尾斜杠要与 location 对齐:alias /data/static/;。用 root 的等价写法是 root /data;(拼完整 URI 得 /data/static/a.png)。加分项:同一 location 不能混用 root 与 alias;正则 location 里的 alias 必须写捕获。

Q3. try_files $uri $uri/ =404; 与 try_files $uri $uri/ 404; 有什么区别?怎么一眼发现写错了?

答案要点:=404 是「把响应码设为 404」,这也是 error_page 404 能接管的正常路径;裸 404 被当成相对 root 的文件名 去 open(),实测错误日志是 open() "/usr/share/nginx/html404" failed。两者现象都是 404,只能靠 error.log 里那条 open() 识别;若站点根恰好有名为 404 的文件,就会返回 200 把内容发出去。同理,SPA 兜底若跳回自身 location,会得到 500 与 rewrite or internal redirection cycle。

Q4. 静态资源站要「HTML 短缓存、带 hash 的 js/css 长缓存、gzip 且 CDN 安全」,关键几行怎么写?每个头说明什么?

答案要点:location /assets/ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable" always; } + location / { expires 10m; try_files $uri $uri/ /index.html; } + gzip on; gzip_comp_level 6; gzip_vary on; gzip_types text/css application/javascript application/json;。Expires 与 Cache-Control: max-age= 是同一语义的两套头(HTTP/1.0 与 1.1),expires 会一起发,别再手写冲突的 max-age;immutable 表示缓存期内不必发条件请求,只对带 hash 的文件名安全;Vary: Accept-Encoding 由 gzip_vary on 产生,缺了它 CDN 可能把 gzip 版发给不支持的客户端;HTML 必须短缓存,文件名不变、长缓存就永远拿不到新版本。

Q5. autoindex on 什么时候可以开?开了之后还有哪两个必做动作?

答案要点:只有确实需要目录浏览 的内部场景(制品库、临时下载区、内网镜像)才开;公网站点默认 off,目录列表等于泄露文件结构与命名规律。必须用精确匹配 的受控 location(如 location = /list/)而不是把整站开成列表,并配 internal 或 allow/deny 白名单。同时调好 autoindex_exact_size off(人读单位)与 autoindex_localtime on(本地时间),否则列表时间是 UTC、排障容易误判;最后检查 default_type 与 charset,避免列表页与文件类型错配。


7. 常见坑

  1. alias 结尾少斜杠 → 404 或 403 → 现象:错误日志里路径两段粘在一起(/usr/share/nginx/htmlindex.html)。根因:alias 是字符串替换,location 有结尾斜杠时余下部分不带 /。正解:location /static/ { alias /data/static/; },两者斜杠同进同退;反过来 location 少斜杠(/static)会误吞兄弟路径 /staticfoo。
  2. try_files 的 =404 写成 404 → 现象:也是 404,但日志里多了 open() ".../html404" failed。根因:末项既无 = 又不以 / 开头,被当成相对 root 的文件名。正解:=404 一个字符都不能省;SPA 用 /index.html 这种内部 URI。
  3. 正则 location 里 alias 忘写捕获 → 现象:下载请求全部 301 到目录,或统一 404。根因:alias /data/files/; 在正则 location 里拿不到 $1,整个 URI 被替换成一个目录。正解:location ~ ^/download/(.+)$ { alias /data/files/$1; }。
  4. alias 与 try_files 混用 → 现象:文件明明在,try_files $uri $uri/ =404; 一律 404(实测如此)。根因:try_files 的路径按 root 解析,与 alias 各拼各的。正解:二选一------用 alias 就别加 try_files;要回退就用 root + try_files(边界细节以官方文档为准)。
  5. expires 与 add_header Cache-Control 并存 → 现象:curl -I 看到两条 Cache-Control(lab 默认配置实测就是 max-age=604800 + public)。根因:expires 自己会发 Cache-Control,add_header 是再追加 一条。正解:要么只用 expires,要么只用 add_header 手写完整 max-age, public, immutable。
  6. 以为 add_header 会累加 → 现象:父级加了安全头,某个 location 里却消失。根因:子级一旦出现 add_header,父级整组都不再继承。正解:公共头写成片段 include,或在每个需要的 location 重复写。
  7. ^~ 与正则的直觉反了 → 现象:以为正则永远优先,结果 /static/img/x.php 走了 ^~ 分支。根因:^~ 的最长前缀命中后直接终止 正则阶段。正解:用 ^~ 明确「这块路径不许正则插手」;要按扩展名分发时别给目录加 ^~。
  8. SPA 兜底吞掉真 404 → 现象:任何乱路径都返回 200 与首页(实测 typo 200)。根因:try_files $uri $uri/ /index.html 是全局兜底,静态资源不存在也回首页。正解:把静态资源收进专门前缀(/assets/、/static/)并在其中用 try_files $uri =404,只让前端路由走回退;SEO 需要真 404 时用 map 按 $uri 是否带扩展名分流(map 见第 6 篇)。

8. 延伸阅读

主题 官方页面
location / root / alias / try_files / index / error_page / internal / etag / if_modified_since / sendfile / directio / output_buffers / merge_slashes / default_type / max_ranges nginx.org/en/docs/htt...
gzip 全家(含 gzip_vary、gzip_comp_level、gzip_min_length)与 gzip_static nginx.org/en/docs/htt... · nginx.org/en/docs/htt...
expires / add_header nginx.org/en/docs/htt...
index / autoindex(含 autoindex_exact_size、autoindex_localtime) nginx.org/en/docs/htt... · nginx.org/en/docs/htt...
charset / charset_types / charset_map / source_charset nginx.org/en/docs/htt...
相关推荐
小满zs1 小时前
Go语言第二十章(初探Gin)
后端·go
学长毕设1 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
小满zs1 小时前
Go语言第十九章(http标准库)
后端·go
考虑考虑3 小时前
nginx拦截url
运维·后端·nginx
GISer_Jing3 小时前
GitHub热点I
后端·ai·langchain
谭光志4 小时前
如何让 AI 高效工作
前端·后端·ai编程
ServBay4 小时前
连AI自己也不愿意维护自己的屎山代码
后端·ai编程·claude
code2cat5 小时前
【随笔】MCP长任务:查询已经返回,为什么任务还没有完成
javascript·人工智能·后端·mcp
Java与AI落地5 小时前
别再正则抠 JSON 了:用 Spring AI 的 entity() 把模型输出变成对象
后端