index指令不支持../路径,因其仅接受相对于root或alias的相对文件名,向上跳转会超出root作用范围而被拒绝;正确方式是统一root、使用alias映射或try_files fallback到公共目录。

不能直接用 index 指令指定父级目录(如 ../index.html)的文件作为默认首页。
为什么 index 不支持 ../ 路径
index 指令只接受相对于 root 或 alias 所设路径的**相对文件名**,不支持向上跳转(..)。Nginx 会将你写的 index ../common/index.html 解析为 $root/../common/index.html,而该路径超出 root 的作用范围,会被安全机制拒绝或返回 403/404。
正确实现“复用父级公共首页”的方式
核心思路是:让不同 location 共享同一个物理根目录,或通过 alias 显式映射到公共文件所在位置。
-
方案一:统一 root 到公共文件所在层级
把所有站点的root设为包含公共首页的父目录,再用子路径区分内容:root /var/www/common;
然后在 location 中用index直接引用:location /site1/ { index index.html; }→ 实际找/var/www/common/index.html -
方案二:用 alias 指向公共目录
对需要共用首页的 location,不用root,改用alias直接映射到公共文件目录:location / { alias /var/www/common/; index index.html; }
此时访问/就会从/var/www/common/下查找index.html -
方案三:用 try_files + 内部重定向(推荐)
保留各 site 独立 root,但 fallback 到公共首页:location / { root /var/www/site1; try_files $uri $uri/ /common/index.html; }
需确保/common/location 已定义并指向公共目录:location = /common/index.html { alias /var/www/common/index.html; }
注意事项
无论哪种方式,都要确认:
- 公共首页文件(如
/var/www/common/index.html)存在且 Nginx 进程有读取权限 - 若使用
alias,末尾斜杠必须与 location 匹配(location /common/ { alias /var/www/common/; }) -
index指令仍需保留,因为try_files $uri/触发目录匹配时,仍依赖index来决定返回哪个文件
本质上,Nginx 的安全模型不允许跨 root 边界自动解析,所以得靠配置结构绕过限制,而不是靠 ../。


















