location匹配

匹配的符号说明
  • = 表示精确匹配,只有完全匹配上才能生效
  • ^~ 表示uri以某个常规字符串开头
  • ~ 正则匹配(区分大小写)
  • ~* 正则匹配(不区分大小写)
  • ! ~ 和! ~ *分别为区分大小写不匹配的正则 、不区分大小写不匹配的正则
  • / 任何请求都会匹配
匹配优先级
  1. 匹配=,如果匹配成功,则停止其他匹配
  2. 普通字符串的匹配,和其在配置文件中的顺序无关,而是与匹配的长短有关,如果匹配成功的location使用了^~,则停止匹配,否则进行正则匹配(如果正则匹配成功,则使用正则匹配的结果,如果正则匹配不成功,则使用此处匹配的结果)
  3. 正则匹配,按照正则匹配在配置文件中出现的顺序,成功则停止匹配
  4. 以上都没匹配成功,则使用/通配符匹配

有时候为了避免匹配成功的普通字符串再继续进行正则匹配,会使用^~符号

实例1
location = / {  
   #规则A  
}  
location = /login {  
   #规则B  
}  
location ^~ /static/ {  
   #规则C  
}  
location ~ \.(gif|jpg|png|js|css)$ {  
   #规则D  
}  
location ~* \.png$ {  
   #规则E  
}  
location !~ \.xhtml$ {  
   #规则F  
}  
location !~* \.xhtml$ {  
   #规则G  
}  
location / {  
   #规则H  
}

访问根目录http://localhost/ 将匹配规则A

访问 http://localhost/login 将匹配规则B,http://localhost/register 则匹配规则H

访问 http://localhost/static/a.html 将匹配规则C

访问 http://localhost/a.gif, http://localhost/b.jpg 将匹配规则D,规则E不起作用,而 http://localhost/static/c.png 则优先匹配到规则C

访问 http://localhost/a.PNG 则匹配规则E,而不会匹配规则D,因为规则E不区分大小写。

访问 http://localhost/a.xhtml 不会匹配规则F和规则G,http://localhost/a.XHTML不会匹配规则G,因为不区分大小写。规则F,规则G属于排除法,符合匹配规则但是不会匹配到。

访问 http://localhost/abc 则最终匹配到规则H

实例2(普通字符串匹配)
location ^~ /helloworld { #1 
	return 601;
} 
#location /helloworld { #2 
# 	return 602;
#}
location ~ /helloworld { 
 	return 603;
}

访问http://localhost/helloworld/test,返回601
如果将上面的块注释,中间的块放开注释,则返回603,因为匹配到普通字符串没有带^~,会继续进行正则匹配

实例3(普通字符串长短匹配规则)
location /helloworld/test/ {
    return 601;
}
        
location /helloworld/ {
    return 602;
}

普通字符串的匹配和配置文件中的顺序无关,而是与匹配的长短有关。

访问http://localhost/helloworld/test/a.html,返回601
http://localhost/helloworld/a.html,返回602

实例4(正则匹配和其在配置文件中的顺序有关)
location /helloworld/test/ { #1
return 601;
}

location ~ /helloworld { #2
return 602;
}

location ~ /helloworld/test { #3
return 603;
}

访问http://localhost/helloworld/test/a.html,返回602
交换#2和#3调换顺序
访问http://localhost/helloworld/test/a.html,返回603

正则匹配

访问根目录下的静态资源时(如http://ip/1.jpg),都会去html目录下找:

location ~ \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {  
#或者
#location ~ /\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {  
   root html; 
}

访问http://img/1.jpg是去html/img目录下找:

location ~ /img/.+\.jpg$ {
    root html;
}

root和alias的区别

root语法规则:

语法: root path;
配置块: http、server、location、if

alias语法规则:

语法: root path;
配置块: http、server、location、if

下面这两种写法的区别(html是nginx的默认访问根目录):

location /dir1/ {
	alias html/dir1;
}
location /dir1/ {
	root html/dir1;
}

当访问http://ip/dir1/1.html的时候,如果是第一种配置,则会在html/dir1目录下找1.html文件,如果是第二种配置,则会在html/dir1/dir1目录下找1.html文件

proxy_pass 加/和不加/

proxy_pass代理的时候,下面两种写法的区别:

location /proxy/ {
    proxy_pass http://proxy_ip;
}
location /proxy/ {
    proxy_pass http://proxy_ip/;
}

当访问http://ip/proxy/1.html的时候,如果是第一种配置,则代理访问http://proxy_ip/proxy/1.html,如果是第二种配置,则代理访问http://proxy_ip/1.html