210. nginx root && alias区别

1.alias
Defines a replacement for the specified location. For example, with the following configuration
location /i/ {
    alias /data/w3/images/;
}
on request of “/i/top.gif”, the file /data/w3/images/top.gif will be sent.
# 他说的很明白, 也就是如果你请求的url是/i/top.gif, 它会访问你的/data/w3/images/top.gif目录去找文件, 也就是localiton后面整个都被alias替代

The path value can contain variables, except $document_root and $realpath_root.

If alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:
# 如果你的location使用了正则表达式, 那么你应该把需要部分使用正则表达式捕获, 在alias中使用正则表达捕获的结果

location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;  # 比如上面()中的内容被捕获使用$1代替(这是正则表达式语法,请学习它)
}
When location matches the last part of the directive’s value:  # 很有意思的是如果你的结束部分直接就是想要的文件的话请使用root, 互相推卸责任

location /images/ {
    alias /data/w3/images/;
}
it is better to use the root directive instead:

location /images/ {   # 意思是使用这个比上面好
    root /data/w3;
}

2.root
Sets the root directory for requests. For example, with the following configuration

location /i/ {
    root /data/w3;
}
The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request.

# 他的意思是请求/i/top.gif, 会访问/data/w3/i/top.gif这个文件, 也就是localiton后面整个都被加到root后面

The path value can contain variables, except $document_root and $realpath_root.  # 他支持变量我不理解$document_root和$realpath_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.  # 很有趣的是这里他说如果你的URI改变了, 那么请使用alias也就是别名
原文地址:https://www.cnblogs.com/liuzhanghao/p/15657252.html