index、try_files 与目录列表
约 584 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 静态资源服务(在新窗口打开) › index、try_files 与目录列表
index
index 指定访问目录时默认返回的文件:
location / {
root /var/www/html;
index index.html index.htm index.php;
}当请求 http://example.com/ 或 http://example.com/about/ 时,Nginx 会依次尝试目录下的 index.html、index.htm、index.php。
try_files
try_files 是 Nginx 最强大的指令之一,按顺序尝试文件/路径,每一项可作为内部重定向到另一个 location:
location / {
try_files $uri $uri/ /index.html;
}| 参数 | 含义 |
|---|---|
$uri | 当前 URI 对应的文件路径 |
$uri/ | 当前 URI 对应的目录(触发 index 逻辑) |
/index.html | 最终兜底,内部重定向到 /index.html |
SPA 应用(Vue/React)配置
server {
listen 80;
server_name app.example.com;
root /var/www/app/dist;
# SPA 核心:所有路由回退到 index.html
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源加上缓存(CSS/JS 文件名带 hash)
location ~* \.(css|js|jpg|png|svg|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}多级回退
location / {
try_files $uri $uri/ /fallback.html @backend;
}
location @backend {
proxy_pass http://backend:3000;
}try_files 支持四种类型:
| 类型 | 示例 | 说明 |
|---|---|---|
| 文件 | $uri | 直接检查文件是否存在 |
| 目录 | $uri/ | 尝试目录 + index |
| 最终 URI | /index.html | 内部重定向 |
| 命名 location | @backend | 跳转到命名 location |
目录列表(autoindex)
location /downloads/ {
alias /var/data/packages/;
autoindex on;
autoindex_exact_size off; # 显示人类可读的大小(KB/MB)
autoindex_localtime on; # 显示本地时间而非 GMT
}| 指令 | 说明 |
|---|---|
autoindex on | 开启目录列表(默认 off) |
autoindex_exact_size on/off | on 显示精确字节数,off 显示约数 |
autoindex_localtime on/off | on 显示本地时间,off 显示 GMT |
综合示例
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
# 普通页面
location / {
try_files $uri $uri/ /index.html;
}
# 下载目录(开启目录列表)
location /downloads/ {
alias /var/data/files/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}小结
index定义目录的默认首页文件(按顺序查找)。try_files按顺序尝试文件/路径/重定向,是 SPA 路由回退和优雅降级的核心。autoindex开启目录列表功能,配上autoindex_exact_size和autoindex_localtime。try_files最后一项可以是@命名 location,实现两级处理逻辑。
上一节:location 匹配规则 下一节:静态资源优化
