0
点赞
收藏
分享

微信扫一扫

location的4种匹配规则

晴儿成长记 2022-02-11 阅读 57

在开始讲之前需要知道我这里有哪些静态资源文件。

先把xpfStatic和foodie-shop静态资源上传到服务器的/home文件夹。其中xpfStatic中有三个文件夹如下。

其中img中有如下照片。这也是本博客中举例用到最多的。

正文开始:

1、空格:默认匹配,普通匹配

#空格:默认匹配
server {
        listen       90;
        server_name  localhost;

        #空格加斜杠/,访问路径为:http://192.168.217.129:90/,默认匹配到静态资源foodie-shop下的index.html
        #第二行 index index.html 可加可不加
        location / {
            root   /home/foodie-shop;
           # index  index.html;
        }

        #此静态资源在服务器上的路径为:/home/xpfStatic/。里面有三个目录/img、/audio、/video。均可访问
        #比如要访问img下的图片。访问路径为:http://192.168.217.129:90/xpfStatic/img/face1.png
        location /xpfStatic{
            root /home;
        }

        #此和上述映射一样。这里使用了alias,使得可以使用别名,而隐藏实际路径。如这里的别名static
        #若要访问img下的图片。访问路径为:http://192.168.217.129:90/static/img/face1.png
        location /static{
            alias /home/xpfStatic;
        }

}

2、: 精确匹配

# = : 精确匹配
server{
        listen          91;
        server_name     localhost;


        #等于号属于精确匹配,以下配置只能访问服务器上的/home/xpfStatic/img/face1.png图片,除此之外访问不了任何其他资源。
        #比如img下的face2.png图片。或者xpfStatic下的其他三个目录的资源
        location = /xpfStatic/img/face1.png{
            root /home;
        }

}

注意和下面讲到的路径匹配 ^~匹配做区分,精确匹配必须匹配到某个文件,而不能是某个路径。

3、正则匹配

 (1)# ~ : 正则表达式,区分大小写

# ~ : 正则表达式,区分大小写
server{
        listen          92;
        server_name     localhost;

        #假设这里要访问http://192.168.217.129:92/xpfStatic/img/face1.png,
        #由于访问路径区分大小写,所以即使服务器img下有face1.png图片资源,也访问不了。
        #必须是大写的face1.PNG才能访问
        location ~ \.(gif|PNG|bmp|jpg|jpeg){
            root /home;
        }
}

(2)# ~* : 正则表达式,不区分大小写

# ~* : 正则表达式,不区分大小写
server{
        listen          93;
        server_name     localhost;

        #假设这里要访问http://192.168.217.129:93/xpfStatic/img/face1.png,
        #即使正则表达式里写的是大写PNG,但只要服务器里有face1.png一样可以匹配的到。
        location ~* \.(gif|PNG|bmp|jpg|jpeg){
            root /home;
        }

}

4、^~  :  以某个字符路径下开头请求,路径匹配

#^~ : 以某个字符路径下开头请求
server{
        listen          94;
        server_name     localhost;

        #^~:非正则。意思是不使用正则表达式。
        #这里指定了只能访问xpfStatic下三个文件资源的 /img 文件夹下的资源,指定路径
        location ^~ /xpfStatic/img{
            root /home;
        }

}
举报

相关推荐

0 条评论