「Nginx杂谈」root和alias的区别

直接翻Nginx的官方文档,再附带个示意图。顺便人肉机翻下。

root

Syntax: root path;
Default: root html;
Context: http, server, location, if in location

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

为你的请求设置根目录。例如,跟在下面的这个配置。

1
2
3
location /i/ {
root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to the /i/top.gif request.

发送/data/w3/i/top.gif用作响应来自/i/top.gif的请求。

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

Path的值可以包含变量,除了$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.

文件的路径是通过向root的值添加URI来构造的。如果要修改URI,应该使用alias指令。

请求https://zsnmwy.net/i/test.png的时候,实际Nginx返回的是服务器上面的/data/w3/i/test.png


alias

Syntax: alias path;
Default: —
Context: location

Defines a replacement for the specified location. For example, with the following configuration

定义特定位置的替换。例如,跟在后面的这个配置

1
2
3
location /i/ {
alias /data/w3/images/;
}

on request of /i/top.gif, the file /data/w3/images/top.gif will be sent.

当请求/i/top.gif,文件/data/w3/images/top.gif将会被发出。

/i/会被替换成/data/w3/images/

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

Path的值可以包含变量,除了$document_root$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:

如果alias在使用了正则表达式的location里面,那么正则表达式应该包含捕抓,alisa应该使用变量去引用这些捕获。

1
2
3
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}

location与最后一个指令的值匹配的时候,

When location matches the last part of the directive’s value:

location与最后一个指令的值匹配的时候:

1
2
3
location /images/ {
alias /data/w3/images/;
}

it is better to use the root directive instead:

最好是使用root指令来代替:

1
2
3
location /images/ {
root /data/w3;
}
0%