Nginx中的root和alias指令该如何使用?
Nginx是一款流行的Web服务器软件,常被用于反向代理。
在Nginx的配置文件中,经常用到root和alias指令,这两个指令有什么区别。下面是一个具体的示例,配置文件如下:
server {
listen 80;
server_name www.aneirin.xyz;
access_log /var/log/nginx/access.log main;
location /a {
root /html;
}
}
在Nginx服务器目录”/html/a“下放置文件”src.txt“,包含内容:“This is a test page!!!”。
访问这个文件,
[aneirin@host-1]$ curl http://www.aneirin.xyz/a/src.txt
This is a test page!!
如果要用alias指令,需要将配置文件的第7行修改成这样,
alias /html/a;
之所以要这样修改,是因为alias指令的作用是给指定的location起一个别名。结合上面的配置文件,简单理解为给“/a”起了个别名“/html/a”。配置文件中的location是”/a“,当访问"/a/src.txt"时,nginx把文件”/html/a/src.txt“返回给客户端。
再举一个例子,如果请求的URL是“
http://www.aneirin.xyz/a/b/src.txt”,nginx配置文件不改,“src.txt”文件应该放到哪个目录?nginx配置文件:
server {
listen 80;
server_name www.aneirin.xyz;
access_log /var/log/nginx/third-access.log main;
location /a {
root /html;
}
#location /a {
# alias /html/a/;
#}
}
答案:“src.txt”应该放到服务器“/html/a/b”目录,大家想想为什么?
“root”和“alias”还有一个区别是“alias”只能放在“location”上下文中,而“root”可以放置在“http”,“server”,“location”上下文中。