nginx的location优先级

nginx下面的location是有优先级的,由高到低如下:

  1. 等号类型(=)的优先级最高(完全一致才算匹配)。一旦匹配成功,则不再查找其他匹配项
  2. ^~类型表达式(前缀匹配)。一旦匹配成功,则不再查找其他匹配项
  3. 正则表达式类型(~ ~*其中~区分大小写 ~*不区分)
  4. 常规匹配

下面是一个典型配置:

user  root;
events {worker_connections  1024;}
http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       8080;
        #优先级第4
        location / {
        content_by_lua 'ngx.say("success4")
ngx.exit(ngx.OK)';
        }
        #优先级第2
        location ^~ /hls
        {
                content_by_lua 'ngx.say("success2")
ngx.exit(ngx.OK)';
        }
        #优先级第3
        location ~* index\.m3u8
        {
                content_by_lua 'ngx.say("success3")
ngx.exit(ngx.OK)';
        }
        #优先级第1
        location = /hls/demo/index.m3u8
        {
                content_by_lua 'ngx.say("success1")
ngx.exit(ngx.OK)';
        }
    }
}

下面是运行结果:

curl http://127.0.0.1:8080/hls/demo/index.m3u8
success1

curl http://127.0.0.1:8080/hls/demo2/index.m3u8
success2

curl http://127.0.0.1:8080/3hls/demo/index.m3u8
success3

curl http://127.0.0.1:8080/hls/demo/index4.m3u8
success2

curl http://127.0.0.1:8080/5hls/demo/index4.m3u8
success4