nginx 中location和root

nginx 中location和root,你确定真的明白他们关系?

最近公司开发新项目,web server使用nginx,趁周末小小的研究了一下,一不小心踩了个坑吧,一直404 not found!!!!!当时卡在location和root中,但是网上却比较少聊这方面的关系,一般都是聊location匹配命令(这里可以看看http://www.nginx.cn/115.html),花了一下午,彻底搞清楚了location和root到底怎样找到文件的。

 

nginx指定文件路径有两种方式root和alias,这两者的用法区别,使用方法总结了下,方便大家在应用过程中,快速响应。root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。

 

 

[root]
语法:root path
默认值:root html
配置段:http、server、location、if

[alias]
语法:alias path
配置段:location

root实例:

 

location ^~ /t/ {
     root /www/root/html/;
}

如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。

 

alias实例:

 

location ^~ /t/ {
 alias /www/root/html/new_t/;
}

如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。

 

注意:

1. 使用alias时,目录名后面一定要加"/"。
3. alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
4. alias只能位于location块中。(root可以不放在location中)

 

 

 

 


server {
        listen       80;
        server_name  119.45.24.70;
#1、项目配置,

            location / {
                  proxy_pass   http://119.45.24.70:8080;
                  #index  index.html index.htm;
            }
            
            #http://test.com/portal    #就相当于访问:http://127.0.0.1:8080/portal
            location /portal {
                  proxy_pass   http://119.45.24.70:8080;
        #          root html;
                 # index  index.html index.htm;
            }   

#如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件
#如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。
#注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。
        location ^~ /t/ {
            alias  /usr/local/nginx/html/first/;  
            index  index.html index.htm;  
        }

#2、页面配置

        location /static/page {
            alias  html/first;  
            index  index.html index.htm;  
        }
        
        
#3、图片配置
location ~.*\.(jpg|jepg|gif|css|png|ico|html)?$ {
             root /usr/local/nginx/sbin/home/images;
             expires 30d;
             break;
        }

    }
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值