root指令会将location块的”url路径”带入到”root指令路径”中,将带入后的路径作为”最终路径”,使用”最终路径”与url建立对应关系。
alias指令则直接将location块的”url路径”与”alias指令路径”建立对应关系。
直接举例说明,更容易理解!!!!
例子1:
location /demo {
root /opt/test;
}
这时,访问http://localhost/demo 相当于访问/opt/test/demo/
例子2:
location /demo1 {
alias /opt/test;
}
这时,访问http://localhost/demo1 相当于访问/opt/test
例子3:
location /view/ {
alias /mnt/test/docker/dist;
}
这时,访问http://localhost/view/时,由于请求URI以/view/结尾且已经包含了末尾斜杠,Nginx在合并时不会自动添加额外的斜杠。结果可能导致Nginx尝试访问类似/mnt/test/docker/distindex.html这样的文件路径,Nginx返回404 Not Found错误
例子4:
location /view {
alias /mnt/test/docker/dist;
}
这时,访问http://localhost/view/时,Nginx会自动在请求URI末尾添加斜杠(如果未显式给出),然后与alias指定的路径合并。在这种情况下,Nginx会正确地尝试访问/mnt/test/docker/dist/index.html,假设你的静态文件实际位于/mnt/test/docker/dist/目录下,此时能够成功找到并返回文件内容
例子5:
location /view/ {
alias /mnt/test/docker/dist/;
}
注意到alias指令后面路径末尾添加了一个斜杠。这样做可以让Nginx在合并请求URI时保持正确的目录结构,从而正确地定位到静态文件。这时,访问http://localhost/view/时,Nginx会尝试访问/mnt/test/docker/dist/index.html,预期能够正常显示登录界面。