Nginx中location root alias用法的区别

413 阅读2分钟

location中使用root和alias

测试文件的目录结构如下:

$ tree /opt/www/
/opt/www/
├── 1.html
└── r
    ├── 2.html
    └── t
        └── 3.html

  • root 配置示例:
location /r/ {
    root /opt/www;
}

官方文档对location中使用root的配置的解释是:

A path to the file is constructed by merely adding a URI to the value of the root directive. If a URI has to be modified, the alias directive should be used.

访问一个文件,其路径仅仅是拼接 root目录路和URI组成的,如果这个URI被修改了,那么需要使用 alias 代替了。

访问如下uri:

http://localhost/1.html response: 404
http://localhost/r/2.html response:200
http://localhost/r/t/3.htlm response:200
http://locahost/r/notexist.html reponse:404

文件1.html在服务器的文件位置是:/opt/www/1.html, 但是root的配置是/r/,路径中必须要拼接上location后面的这个配置,文件1.html的路径中没有/r/,所有文件1.html访问不到,而文件2.html在服务器的位置是/opt/www/r/2.html,location的配置/r/是root的配置的/opt/www的子目录,可以匹配,后面继续拼接上资源路径即可,如:http://localhost/r/2.html对应的服务器的资源地址是/opt/www/r/2.htmlhttp://localhost/r/t/3.html映射的服务器资源地址是opt/www/r/t/3.html

总结

location和root组合相当于在root指定目录下进行location匹配,location所匹配内容必须保证在root指定目录的子目录,否则配置无效,而且location只能向下匹配,不能匹配location指定目录上一级目录中的内容。

  • alias 配置示例:
location /bus {
        alias   /opt/www;
    }

官方文档对alias的配置解释:

Defines a replacement for the specified location.

对location指定一个别名来替代。这就是上面root配置里面,文档说如果URI被修改了,那么需要使用alias来配置替换。

访问:

http://localhost/bus/1.html
respnse:200

http://locahost/bus/r/2.html
response:200

http://localhost/bus/r/t/3.html
response:200

文件1.html在服务器的文件位置是:/opt/www/1.html, alias用/bus这个URI代替/opt/www 这个路径, 所以http://localhost/bus/1.html 就相当于访问了Linux服务器的 /opt/www/1.html 这个资源
同理,/bus/r/2.html 就是访问服务器的/opt/www/r/2.html这个资源

总结 location与alias组合,需要保证location匹配目录与alias指定目录级别相同,否则配置无效,与location和root组合相同的是,location所匹配内容也只能向下匹配。

注意

1, 很多文章说,alias配置文件路径的时候,最后要加上反斜杠,"/",我实验的时候不加也能访问到,严谨一些的话加上也可以