Back
Please upgrade your browser or check your network connection.

「Nginx杂谈」root和alias的区别

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

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

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

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

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

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

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 应该使用变量去引用这些捕获。

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

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

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

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

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

it is better to use the root directive instead:

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

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