location规则
location是nginx的精华,nginx就是通过拦截到的请求去对配置好的location块(location block)进行请求代理的。
location是用来具体配置代理路径的,具体格式如下:
location [=|~|~*|^~|@] /uri/ { … }
语法规则:
= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求
为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~* 开头表示不区分大小写的正则匹配
!~ 区分大小写不匹配正则
!~* 不区分大小写不匹配正则
/ 通用匹配,任何请求都会匹配到。
Localtion的匹配规则的优先级
首先匹配 =
其次匹配 ^~
其次是按文件中顺序的正则匹配,
最后是交给 / 通用匹配。
当有匹配成功时候,停止匹配,按当前匹配规则处理请求。
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
实例:
若是用源码安装的nginx测试,则需要添加echo模块
模块:https://github.com/openresty/echo-nginx-module
[root@nginx1 ~]# ls
v0.61.tar.gz
[root@nginx1 ~]# tar xf v0.61.tar.gz -C /usr/local/src/
[root@nginx1 ~]# systemctl stop nginx
[root@nginx1 ~]# nginx -V
nginx version: nginx/1.15.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/opt/data/nginx --with-http_stub_status_module --with-http_ssl_module --with-stream
[root@nginx1 ~]# cd /usr/local/srcnginx-1.15.0/
[root@nginx1 nginx-1.15.0]# ./configure --prefix=/opt/data/nginx --with-http_stub_status_module --with-http_ssl_module --with-stream --add-module=/usr/local/src/echo-nginx-module-0.61
[root@nginx1 nginx-1.15.0]# echo $?
0
[root@nginx1 nginx-1.15.0]# make # 不要make install
[root@nginx1 nginx-1.15.0]# echo $?
0
[root@nginx1 nginx-1.15.0]# cp objs/nginx /opt/data/nginx/sbin/nginx
[root@nginx1 nginx-1.15.0]# systemctl start nginx
配置文件:
[root@nginx1 ~]# cd /opt/data/nginx/conf/conf.d
[root@nginx1 conf.d]# vim test1.conf
server {
listen 192.168.10.21:80;
server_name www.test1.com;
access_log /opt/data/nginx/data/test1/log/access.log combined;
#location / {
# root /opt/data/nginx/data/test1/basic;
# index index.html index.htm;
#}
location / {
echo "/";
}
location =/ {
echo "=/";
}
location =/nginx {
echo "nginx";
}
location ~ \.(gif|jpg|png|css|js)$ {
echo "small: gif/jpg/png/js";
}
location ~* \.png$ {
echo "all:png";
}
location ^~ /abc/ {
echo "abc";
}
}
[root@nginx1 conf.d]# systemctl restart nginx
测试:可以配置主机hosts文件:C:\Windows\System32\drivers\etc\hosts
(1)输出www.test1.com,精确匹配,因为url默认后面带一个/
(2)输入www.test1.com/123匹配到的是/,此时匹配时先跳过/,依次向下匹配,最终没有匹配到,则会匹配/
(3)输入www.test1.com/abc/ 匹配到 ^~ /abc/ 。注意:此处abc后不加/则默认匹配到/,区分大小写匹配正则