root指令指定静态资源物理根目录,Nginx将请求URI原样拼接到该路径后查找文件;可置于http/server/location块,优先级location>server>http;必须配合index指令才能使/自动加载index.html。

Linux 下 Nginx 的 root 指令用于指定静态资源在服务器上的**物理根目录路径**,Nginx 会把请求的 URI(如 /css/style.css)原样拼接到这个路径后面,去磁盘上查找真实文件。
root 的基本配置位置和写法
root 必须写在 http、server 或 location 块中,推荐使用绝对路径:
-
正确写法:
root /var/www/myapp;(末尾可加可不加斜杠,但保持统一更稳妥) -
避免相对路径:
root html;会相对于 Nginx 安装前缀解析(如/usr/local/nginx/html),容易出错 - 优先级:location > server > http。若 location 内写了 root,就以它为准;没写则继承上层
root 是怎么拼出真实文件路径的
Nginx 不做路径截断或替换,只做“拼接”:
- 配置:
root /srv/site; - 访问
/about/team.html→ 查找/srv/site/about/team.html - 访问
/→ 查找/srv/site/index.html(前提是启用了index index.html;) - URI 开头的
/不参与拼接,只取其后部分
为不同 URL 前缀设置独立根目录
用多个 location 块配合 root,可实现多资源目录映射:
-
location /images/ { root /data/pics; }→ 请求/images/logo.png查找/data/pics/images/logo.png -
location /uploads/ { root /opt/storage; }→ 请求/uploads/file.pdf查找/opt/storage/uploads/file.pdf - 注意:这种写法要求目标目录下存在与 URI 前缀同名的子目录
关键注意事项
- Nginx 工作进程用户(如
www-data或nginx)必须对 root 指定目录有读取权限 - 单独使用 root 无法让
/自动显示首页,必须搭配index index.html;指令 - 如果想让
/static/直接对应/var/www/static/这类“去掉前缀”的效果,应改用alias而非root


















