目录
1、alias 语法
Syntax: alias path;
Default: —
Context: location
定义指定location的替换。例如,使用以下配置
location /i/ {
alias /data/w3/images/;
}
当请求 “/i/top.gif
” 时 ,文件/data/w3/images/top.gif将会被发送
path值可以包含变量,除了$document_root和$realpath_root。
如果在一个用正则表达式定义的位置内使用alias,那么该正则表达式应该包含捕捉,而alias应该引用这些捕捉(0.7.40),例如:
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}
当location匹配指令值的最后一部分时:
location /images/ {
alias /data/w3/images/;
}
最好使用根指令
location /images/ {
root /data/w3;
}
2、root 语法
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
设置请求的根目录。例如,使用以下配置
location /i/ {
root /data/w3;
}
/data/w3/i/top.gif
文件将被发送来响应 “/i/top.gif
” 请求。
path值可以包含变量,除了$document_root和$realpath_root。
只需向根指令的值添加一个URI,就可以构造文件的路径。如果必须修改URI,应该使用alias指令。
3、差别
root 会将完整的url 映射进文件路径中.
alias 只会将location 后的URL 映射到文件路径.
4、例子
location /root {
root html;
}
location /alias {
alias html;
}
location ~ /root/(\w+\.txt) {
root html/first/$1;
}
location ~ /alias/(\w+\.txt) {
alias html/first/$1;
}
a、访问 /root/ ,实际访问的时 /root/html/index.html 文件.
[root@zk02 ~]# curl localhost/root/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
b、访问/root/1.txt ,实际访问的是 html/first/root/1.txt
c、访问 /alias/ 实际访问的是 html/index.html
[root@zk02 ~]# curl localhost/alias/
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
4、访问 /alias/1.txt ,实际访问的是 html/first/1.txt
[root@zk02 ~]# curl localhost/alias/1.txt
hello world