Nginx配置中location、root和alias的关系一直很让人困惑,查询好多资料也没能搞明白,于是自己进行了实际操作、总结如下。
1、root指令:
说明:在location和root上,后面可以带/ 也可以不带/ ,效果一样。
# tree /data/root/
/data/root/
├── file1.html
└── r
├── file2.html
└── t
└── file3.html
- http://9.135.136.52/ :openresty默认首页;
- http://9.135.136.52/file1.html :404,因为在/usr/local/openresty/nginx/html/ 目录下没有file1.html(nginx默认的静态目录在/usr/local/openresty/nginx/html/)
- http://9.135.136.52/r/file1.html :404,因为在/data/root/r目录下找不到file1.html文件;
- http://9.135.136.52/r/file2.html :访问/data/root/r/file2.html页面;
- http://9.135.136.52/r/t/file3.html : 访问/data/root/r/t/file3.html页面;
总结:location和root组合相当于在root指定目录下进行location匹配,location所匹配内容必须保证在root指定目录的子目录,否则配置无效,而且location只能向下匹配,不能匹配location指定目录上一级目录中的内容。
2、alias指令:
说明:location后面可以带/也可以不带/,效果一样;
注意事项:
- 使用alias,目录名后面一定要加“/”
- alias只能在location中使用
# tree /data/alias/
/data/alias/
├── a
│ └── file1.html
├── file1.html
└── r
└── file2.html
- http://9.135.136.52/a/file1.html :访问/data/alias/目录下的file1.html页面;
- http://9.135.136.52/a/a/file1.html :访问/data/alias/a/a/file1.html页面;
- http://9.135.136.52/a/r/file2.html : 访问/data/alias/a/r/file2.html页面;
总结:location与alias组合,需要保证location匹配目录与alias指定目录级别相同,否则配置无效,与location和root组合相同的是,location所匹配内容也只能向下匹配。
2.3)root和alias区别:
root:
location ^~ /appImg/{
root /home/nginx;
}
这个location相当于访问服务器上的文件路径: /home/nginx/appImg/abc.jpg 。
alias:
location ^~ /appImg/{
alias /home/nginx/;
}
这个location相当于访问服务器上的文件目录:/home/nginx/abc.jpg(即alias不会使用location后面配置的路径)。而且如果alias 指定的是目录,后面一定要加上 "/"。。。
参考:
https://cloud.tencent.com/developer/article/1409734