Nginx需显式配置index指令才能将index.html作为默认首页,否则访问/返回403或404;必须在location块中设置index、root(或alias)路径正确,并配合try_files实现SPA路由兜底。

Nginx 不会自动把 index.html 当作默认首页,必须显式配置 index 指令,否则访问 / 会返回 403 或 404。
location 块里加 index 指令
- 在对应路径的
location块中写明index,例如:location / { root /var/www/my-site; index index.html index.htm; } - 这行必须存在,缺了就找不到首页;只写
index.html最稳妥,多个文件用空格分隔,按顺序匹配。
root 路径要指向含 index 文件的目录
- 如果
index.html在/var/www/my-site/index.html,root就得设为/var/www/my-site(不能多也不能少一级) - 若用
alias,注意它会完全替换路径,index文件必须直接落在alias指向的目录里
确保 server 块生效
-
server块需有listen 80;(或你访问时用的端口),否则配置不加载 -
server_name要匹配请求 Host,本地测试可暂时删掉或设为空,避免匹配失败
配合 try_files 防止静态资源 404
- 单靠
index只管/这种目录请求,前端路由或 SPA 需加兜底:location / { root /var/www/my-site; index index.html; try_files $uri $uri/ /index.html; }
验证是否生效
- 改完运行
nginx -t检查语法,再nginx -s reload - 用
curl -I http://localhost看状态码和Content-Type - 查错误日志:
tail -f /var/log/nginx/error.log,常见提示如 “open() … failed (13: Permission denied)” 表示权限或路径问题


















