参考资料

  1. 如何查看nginx主配置文件路径方式
  2. Nginx负载均衡策略详细说明以及案例
  3. Nginx日志记录配置指令详细说明以及案例
  4. NginxWebDAV模块配置详细说明以及案例
  5. Nginx expires、etag、if_modified_since:客户端缓存控制详细说明以及案例
  6. Nginx作为反向代理的功能
  7. Nginx请求频率限制模块详细说明以及案例
  8. 如何结合WAF使用Nginx提高安全性?

root指令用于指定Nginx服务器上文件的根目录。当Nginx处理请求时,会根据root指令指定的路径来查找请求的文件。

语法

root path;
  • path:指定文件系统的绝对路径或相对路径。

示例

假设Nginx配置文件位于/etc/nginx/nginx.conf,并且网站文件存放在/var/www/html目录下。

1. 基本配置

server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    location / {
        index index.html;
    }
}
  • 当访问http://example.com/index.html时,Nginx会在/var/www/html目录下查找index.html文件。

2. 多个location

server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    location / {
        index index.html;
    }

    location /images/ {
        root /var/www/images;
    }
}
  • 当访问http://example.com/images/logo.png时,Nginx会在/var/www/images/images/logo.png路径下查找文件。

3. 使用相对路径

server {
    listen 80;
    server_name example.com;

    root html;

    location / {
        index index.html;
    }
}
  • 如果Nginx的配置文件位于/etc/nginx/nginx.conf,则html路径会被解析为/etc/nginx/html

注意事项

  • root指令指定的路径是相对于Nginx配置文件的路径,除非使用绝对路径。

  • 如果root指令在location块中定义,则它会覆盖server块中的root指令。

  • 确保Nginx进程对root指定的目录有读取权限。