root和alias区别详解

root指令

location /blog/ {
        root /usr/local/nginx/html;
        index index.html index.htm;
}

请求 http://127.0.0.1:80/blog/root.html 这个地址时,那么在服务器里面对应的真正的资源是 /usr/local/nginx/html/blog/root.html文件。可以发现真实的路径是root指定的值加上location指定的值

alias指令

location /blog/ {
        alias /usr/local/nginx/html/;
        index index.html index.htm;
}

同样请求http://127.0.0.1:80/blog/alias.html时,在服务器查找的资源路径是:/usr/local/nginx/html/alias.html。正如其名,alias指定的路径是location的别名,不管location的值怎么写,资源的真实路径都是alias指定的路径。

注意:

  1. alias后面必须要用 “/” 结束,不然会被认为是个文件,而找不到对应的目录;而root则对 “/” 可有可无
  2. alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用
  3. alias只能作用在location中,而root可以存在server、http和location中;

root与alias的主要区别

root与alias主要区别是如何解释location后面的uri:

  1. root的处理结果:root路径+location路径
  2. alias的处理结果:使用alias路径替换location路径
  3. alias是一个目录别名的定义,root则是最上层目录的定义。
posted @ 2025-08-14 21:44  阿峰博客站  阅读(35)  评论(0)    收藏  举报