天天看点

nginx之location规则详解

1.nginx执行过程

nginx之location规则详解

首先,浏览器访问一个url;

然后,图中虚拟主机匹配过程。进入到对应的nginx配置的虚拟机主机(也就是/etc/nginx/conf.d/下面的哪个虚拟主机);

其次,图中location匹配。进入到对应的虚拟主机里面的location进行匹配,会分为匹配到的path和未匹配到的path。

2.location中root和alias命令(静态文件处理)

root命令:root后面路径+location路径进行查找(默认是安装nginx时的html目录,建议生产环境写绝对路径);

alias命令:只在alias后面目录查找html文件

#vim smallboy.conf
    server {
        listen       80;
        server_name  www.smallboy.com;

       #访问路径:http://www.smallboy.com/static/a.html
       location /static { #匹配路径/static 剩余路径/a.html
               root html/; # root声明:会在html文件夹下,查找/static/a.html
       }
       #访问路径:http://www.smallboy.com/target/a.html
       location /target { #匹配路径/target 剩余路径/a.html
               alias html/static/; #alias声明:在html/static目录下面查找a.html
       }

    }
           

访问:http://www.smallboy.com/static/a.html

nginx之location规则详解

访问:http://www.smallboy.com/target/a.html

nginx之location规则详解

3.proxy_pass转第三方

① 访问路径:http://www.smallboy.com/nginx/enjoy/getInfo 命中路径/nginx/enjoy path1= /nginx/enjoy,path2=/getInfo, proxy_pass http://192.168.211.165:8081 未关闭,传递path1+path2到后段ip+port

nginx之location规则详解

② 访问路径:http://www.smallboy.com/target/nginx/enjoy/getInfo 命中路径/target path1=target,path2=/nginx/enjoy/getInfo proxy_pass http://192.168.211.165:8081/ 已关闭,传递path2到后端ip+port

nginx之location规则详解

③ proxy_pass关闭不关闭只是针对ip+port后面有没有/而言的。

4.location匹配优先级

精准匹配规则:

nginx之location规则详解

精准匹配测试:

访问:http://www.smallboy.com/wanglei/a/b/c 返回402

nginx之location规则详解

普通匹配规则:

nginx之location规则详解

普通匹配测试:

访问 http://www.smallboy.com/match/a/b/c 返回码414

nginx之location规则详解

正则匹配规则:

nginx之location规则详解

正则匹配测试:

访问http://www.smallboy.com/rex/a/b/c.htm 返回码为500

nginx之location规则详解

server {
listen       80;
server_name  www.smallboy.com;

# 精准匹配测试
# 第1、2条虽然满足,但第三条是精准匹配,出第三条结果 
# 测试路径 /wanglei/a/b/c
location ~ /wanglei/* { #正则表达式匹配上路径
       return 400;
}
location /wanglei/a/b { #普通规则匹配上
       return 401;
}
location = /wanglei/a/b/c { #命中,精准匹配上
       return 402;
}

# 普通匹配测试
# 第1、2条虽然匹配,但第三条匹配更长,出第三条结果
# 测试路径 /match/a/b/c
location /match/a { #被匹配,但不是最长
       return 412;
}
location /match/a/b { #被匹配,但不是最长
       return 413;
}
location /match/a/b/c { #被匹配,且最长
       return 414;
}


#正则匹配覆盖普通匹配测试
#正则匹配会覆盖普通匹配,但不会覆盖=和^~
location = /re/a.js { #访问/re/a.js,直接命中,不会被后面正则匹配上
       return 420;
}
location ^~ /re/a/b { #访问/re/a/b,直接命中,不会被后面正则覆盖
       return 421;
}
location /re/a.htm { #访问/re/a.htm,会被后面正则覆盖
       return 422;
}
location ~ /re/(.*)\.(htm|js|css)$ { #覆盖/re/a.htm
       return 423;
}

#正则匹配成功一条后,便不在走其他正则
#最长正则匹配是第三个,但匹配第一个后便不往下走
#测试路径/rex/a/b/c.htm
location ~ /rex/.*\.(htm|js|css)$ { #匹配上这个后,其他不匹配
       return 500;
}
location ~ /rex/a/(.*)\.(htm|js|css)$ { #匹配上第一个后,不往下进行
       return 501;
}
location ~ /rex/a/b/(.*)\.(htm|js|css)$ { #匹配上第一个后,不往下进行
       return 502;
}