WEB服务与NGINX(5)- root和alias的区别详解
root和alias的区别
-
root:指定站点家目录,给定的路径对应于location中的/uri 左侧的/,文件的绝对路径为root+location。
支持环境:http, server, location, if in location
#1.nginx的配置文件如下: [root@nginx01 ~]# vim /etc/nginx/conf.d/virtualhost.conf server { listen 80; server_name www.nginx01.com; location / { root /data/nginx/html/web1; index index.html; } location /images { root /data/nginx/html/web1/pictures; index index.html; } } #2.nginx的目录结构: [root@nginx01 ~]# cd /data/nginx/html/web1/ [root@nginx01 web1]# mkdir pictures [root@nginx01 web1]# echo "jpg" > pictures/test.html #3.重启nginx [root@nginx01 web1]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@nginx01 web1]# systemctl reload nginx.service #4.此时客户端请求下面的资源时会报404错误,因为在web1下没有images目录 [root@xuzhichao ~]# curl http://www.nginx01.com/images/test.html <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.20.1</center> </body> </html> #5.如果在pictures下新建一个images目录,把test.html放在images目录下,则可以正常访问 [root@nginx01 web1]# mkdir pictures/images [root@nginx01 web1]# mv pictures/test.html pictures/images/ [root@nginx01 web1]# tree pictures/ pictures/ └── images └── test.html [root@xuzhichao ~]# curl http://www.nginx01.com/images/test.html jpg
-
alias:定义路径别名,会把访问的路径重新定义到期指定的路径
注意:在使用alias的时候,location后的uri后面如果加了斜杠,则下面alias定义的路径也必选加斜杠,否则会提示403
仅能用于location上下文
#1.nginx的配置如下 [root@nginx01 web1]# vim /etc/nginx/conf.d/virtualhost.conf server { listen 80; server_name www.nginx01.com; location / { root /data/nginx/html/web1; index index.html; } location /images { alias /data/nginx/html/web1/pictures; index index.html; } } #2.重启nginx进程 [root@nginx01 web1]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@nginx01 web1]# systemctl reload nginx.service #3.web1下的目录文件如下: [root@nginx01 web1]# tree pictures/ pictures/ └── images └── test.html #4.此时客户端请求下面的资源时会报404错误,因为在web1下没有images目录 [root@xuzhichao ~]# curl http://www.nginx01.com/images/test.html <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.20.1</center> </body> </html> #5.如把web1的目录结构改成下面的,则客户端可以正常访问 [root@nginx01 web1]# tree . . ├── index.html └── pictures └── test.html [root@xuzhichao ~]# curl http://www.nginx01.com/images/test.html jpg