参考:https://blog.csdn.net/u011510825/article/details/50531864

作者:果汁华的博客

nginx指定文件路径有两种方式root和alias,这两者的用法区别,使用方法总结了下,方便大家在应用过程中,快速响应。root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。

root 实例:

location ^~ /t/ {
     root /www/root/html/;
}

如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。

alias实例:

location ^~ /t/ {
 alias /www/root/html/new_t/;
}
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。

关于alias的使用场景:

例如:fastdfs的使用,默认情况下上传文件后,会返回一个group1/M00/00/00/XXXXXXXX的路径,但实际系统上,并没有group1/M00的路径,此时我们使用location定位路径的时候,如果使用root的话,服务器返回路径就是/root定位路径/group1/M00/XXXXXXX,因为系统根本不存在此路径,会导致404 nof found ,此时我们就必须使用alias 直接把URL地址替换丢绝对路径(fastdfs文件存放路径)

location ~/group([0-9])/M00 {
            #root /app/fastdfs/storage/data/;       #错误
            #alias /app/fastdfs/storage/data/;      #正确
            #ngx_fastdfs_module;                          #通过模块也可以
}