nginx模块,配置指令,块之间的关系

安装nginx以后,nginx会提供一个默认server,我们可以从nginx.conf文件中找到这个默认server的相关配置,如下:

server {
    listen       80;
    server_name  localhost;
 
    location / {
        root   html;
        index  index.html index.htm;
    }
 
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
 
}

一个http块中可以配置多个server块,一个server块中可以配置多个location,这里配置一个新的location:

[root@server1 conf]# vim nginx.conf
 写入:
 41         location /demo {
 42             root   /opt;
 43             index  index.html index.htm;
 44         }

这个location对应的url为/demo,此location块中的root /opt;配置指令表示这个location的文档根目录为/opt目录,所以,当我们在浏览器中访问/demo/a.png这个url时,访问的其实是服务器中的/opt/demo/a.png文件

在服务器上创建/opt/demo/目录,并且在此目录中创建了一个名为index.html的文件,index.html内容如下:
mkdir /opt/demo

cd /opt/demo/
vim index.html
写入:www.westos.org

之后执行nginx -s reload命令重载配置,重载配置以后,在浏览器中访问链接地址http://172.25.1.1/demo/,效果如下:
在这里插入图片描述
自定义的location已经生效了,当我们访问http://172.25.1.1/demo/这个url时,即可访问到服务器的/opt/demo/index.html文件,在同一个web服务中,我们可以将不同的url对应到不同的服务器路径中,上例中,除了默认的location,我们又手动配置了一个新的location,默认的location为/,我们手动配置的新的location为/demo,所以,访问这两个url时,会分别对应的不同的文档根目录,从不同的目录中查找对应的资源,又因为index配置指令的原因,会默认访问对应目录中的index.html文件或index.htm文件。

同时,默认的location和新加入的location中,index配置指令的值是完全相同的,由于这两个location的index配置完全相同,所以,可以把这个index配置项提取到上一级的server块中,以便这两个location共享这个index配置,配置如下:

  server {
        listen       80;
        server_name  localhost;
 
        location / {
            root   html;
            index  index.html index.htm;
        }
 
        location /demo {
            root   /opt;
            index  index.html index.htm;
        }
 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 }

将index配置指令提取到了这两个location块的上一级server块中,以便两个location块能够共享这个index配置,换句话说就是,server块中的index指令是对当前server块中的所有location生效的,当然,如果某个location块中有自己的index配置,那么针对当前location块来说,还是以自己的index配置为准,比如如下配置:

server {
        listen       80;
        server_name  localhost;
        index  index.html index.htm;
        location / {
            root   html;
        }
        location /demo {
               root /opt;
               index a.png;
          }
    }

上述配置中,server块中index配置是对当前server块中的所有location块生效的,但是由于 location /demo中有自己的index配置,那么针对 location /demo来说,自己的index配置的优先级更高,自己的index配置会覆盖上一级的index配置,所以,当我们访问/demo这个url时,默认会在对应的目录中查找a.png这个文件,而不是index.html文件,但是另外一个location中由于没有配置index指令,所以它仍然会以上一级server块中的index配置为准。此时在浏览器访问http://172.25.1.1/demo/:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值