nginx的优先匹配规则
nginx的优先匹配规则
以=开头表示精确匹配
如 A 中只匹配根目录结尾的请求,后面不能带任何字符串。
^~ 开头表示uri以某个常规字符串开头,不是正则匹配
~ 开头表示区分大小写的正则匹配;
~* 开头表示不区分大小写的正则匹配
/ 通用匹配, 如果没有其它匹配,任何请求都会匹配到
顺序不等于优先级:
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
# 第一个必选规则
一般会nginx代理多个tomcat,有一个作为首页,其余的只作为接口相互调用。
1
2
3
4
|
location /cms {
index.html html
proxy_pass http: //tomcat :8080;
}
|
第二种是静态,当然也有使用静态做首页的,都是死的,点了也不会跳转的,直接映射本地目录。
1
2
3
4
5
6
|
location ^~ /static/ {
root /webroot/static/ ;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/ ;
}
|
第三种就是动静分离:
静态服务器放静态资源,nginx做反代:静态服务器访问本地静态资源,开启80端口。
1
2
3
4
5
6
7
8
|
location = / {
root /data/www ;
}
nginx web service做代理:
location = / {
index.html html
proxy_pass http: //static server:80;
}
|
第四种就是接口调用,nginx代理tomcat。
1
2
3
|
location /api {
proxy_pass http: //tomcat :8080/;
}
|
举一个简单的例子优先匹配规则,不能完全模仿生产,开发需求访问www.xxx/cms,如果是*.html的都跳到静态资源,其他的都跳到tomcat pool;当然静态资源和tomcat pool下面都有index.html文件。在自己的测试机试了下可以做到。
1
2
3
4
5
6
7
8
9
10
11
|
[[email protected] conf.d] # cat admin.conf
server {
listen 80;
server_name localhost;
location /cms {
root /data/www ;
}
location ~* /cms/ .*\.html$ {
root /data/222 ;
}
}
|
目录下面的文件内容如下:
1
2
3
4
5
6
|
[[email protected] conf.d] # ls
admin.conf default.conf.bak
[[email protected] conf.d] # cat /data/222/cms/index.html
2
[[email protected] conf.d] # cat /data/www/cms/index.html
index1
|
测试访问url:http://172.16.2.24/cms/,看它默认跳转。
测试成功,跟书写顺序无关,优先匹配。