nginx 之 root 和 alias

目录

1、alias 语法

2、root 语法

3、差别


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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值