nginx 配置|Nginx Location命令学习笔记

更新时间:2019-02-14    来源:nginx    手机版     字体:

【www.bbyears.com--nginx】

location匹配命令

~      #波浪线表示执行一个正则匹配,区分大小写

~*    #表示执行一个正则匹配,不区分大小写

^~    #^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录

=      #进行普通字符精确匹配

location 优先级官方文档

1. Directives with the = prefix that match the query exactly. If found, searching stops.

2. All remaining directives with conventional strings, longest match first. If this match used

the ^~ prefix, searching stops.

3. Regular expressions, www.111cn.net in order of definition in the configuration file.

4. If #3 yielded a match, that result is used. Else the match from #2 is used.

例如

    location  = / {

        # 只匹配"/".

       [ configuration A ]

    }

    location  / {

        # 匹配任何请求,因为所有请求都是以"/"开始

        # 但是更长字符匹配或者正则表达式匹配会优先匹配

        [ configuration B ]

    }

    location ^~ /images/ {

        # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location

        [ configuration C ]

    }

    location ~* .(gif|jpg|jpeg)$ {

        # 匹配以 gif, jpg, or jpeg结尾的请求.

        # 但是所有 /images/ 目录的请求将由 [Configuration C]处理. 

       [ configuration D ]

    }
 
 
注意:多个location配置的情况下匹配顺序为

1、首先匹配 =,其次匹配常规字符串, 其次是正则匹配。
2、精确匹配当有匹配成功的时候,停止匹配。
3、常规字符串匹配长度优先,越长优先级越高,其中以^~开头的匹配成功后不再进行正则匹配;/ 任何请求

都会匹配到;nginx 不对 url 做编码,因此请求为 /static/20%/aa,可以被规则 ^~ /static/ /aa 匹配到

(注意是空格)。
4、正则匹配当有匹配成功时候,停止匹配,按当前匹配规则处理请求。

本文来源:http://www.bbyears.com/caozuoxitong/48007.html