Nginx 默认首页与目录列表
访问站点根目录(如 http://host/)时,Nginx 按 index 指令查找默认首页;找不到首页且开启 autoindex 时,会直接生成目录列表页。本章把 index、try_files、autoindex 一起讲透。
index:指定默认首页
index 可写多个文件,Nginx 从左到右依次尝试,先找到存在的文件即命中:
server {
listen 80;
server_name example.com;
root /var/www/site;
index index.html index.htm; # 优先 index.html,不存在再看 index.htm
}
目录下同时存在两个文件时用 index.html。注意:只有请求以 / 结尾(即请求目录)时才会触发 index 查找,直接访问 /index.html 不会经过该逻辑。
try_files:找不到文件时的回退
try_files 按参数顺序检查文件/目录是否存在,全部失败则交给最后一个参数处理(可返回状态码或再次匹配 location):
location / {
try_files $uri $uri/ /index.html; # 真实文件 → 目录首页 → 兜底 /index.html
}
典型用途是单页应用(SPA)回退:Vue/React 打包后只有一个 index.html,前端路由由 JS 控制,任何深链都应返回 index.html 再由 JS 渲染:
location / {
try_files $uri $uri/ /index.html; # 深链刷新不 404 的标准写法
}
autoindex:开启目录列表
目录里没有 index 文件时,默认访问返回 403 Forbidden;开启 autoindex 后,访问目录会生成文件列表页:
location /download/ {
root /var/www;
autoindex on; # 开启目录浏览(默认 off)
autoindex_exact_size off; # 大小显示为 5K/1M 人类可读格式(默认 on 显示精确字节)
autoindex_localtime on; # 时间显示本地时区(默认 off 显示 UTC)
}
访问 http://host/download/ 即可看到文件列表、大小与修改时间。
完整示例:下载目录 + SPA 回退
一个站点内 /download/ 开放目录列表,其余路径全部交给前端路由:
server {
listen 80;
server_name dl.example.com;
root /var/www/site;
location /download/ {
autoindex on; # 仅此目录可浏览
}
location / {
try_files $uri $uri/ /index.html; # 其余请求走 SPA 兜底
}
}
验证命令:
curl -s http://127.0.0.1/download/ | head -5 # 看到目录列表 HTML 即生效
curl -I http://127.0.0.1/emptydir/ # 无 index 且 autoindex off → 403
# 输出:HTTP/1.1 403 Forbidden
小结:index 决定"默认显示哪个文件",try_files 决定"找不到文件怎么办",autoindex 决定"要不要把目录列出来"。三者配合即可覆盖默认首页与目录访问的绝大多数场景。