1、location 作用

location 指令的作用是根据用户请求的URI来执行不同的应用。URI的知识前面章节已经讲解过,其实就是根据用户请求的网站地址URL进行匹配,匹配成功即进行相关的作。

2、location 语法

location [ = | ~ | ~* | ^~ | @ ] uri {
........
}

location :指令
[ = | ~ | ~* | ^~ | @ ] :匹配标识
uri:匹配的网站地址
{.....}:匹配URI后要执行的配置段

3、location匹配实战

server {
        listen       80;
        server_name  www.kang.com;
        location / {
            return 401;
	}
	location = / {
 	    return 402;
	}
	location /documents/ {
	    return 403;
	}
	location ^~ /images/ {
	    return 404;
	}
	location ~* \.(gif|jpg|jpeg)$ {
	    return 500;
	}
}

实验结果如下:

[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com
402       #返回402,即匹配了:location = /{ return 402;}
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/
402       #返回402,即匹配了:location = /{ return 402;}
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/index.html
401       #返回401,即匹配了:location / { return 401;}
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/documents/document.html
403       #返回403,即匹配了:location /documents/ { return 403; }
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/documents/1.jpg
500       #返回500,即匹配了:location ~* \.(gif|jpg|jpeg)$ { return 500; }
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/images/1.jpg
404      #返回404,即匹配了:location ^~ /images/ { return 404; }   优先级最高 
[root@localhost nginx-1.6.3]# curl -s -o -I -w "%{http_code}\n" http://www.kang.com/bbs/
401       #返回401,即匹配了:location / { return 401;}

4、匹配优先级顺序

1、“location = / {}“ :精确匹配。 2、"location ^~ /images/ {}" :匹配常规字符串images后,不做其它正则匹配检查。 3、"location ~* .(gif|jpg|jpeg)$ {}":正则匹配。 4、“location /documents/ }{}”:匹配常规字符串,如果有正则,则优先匹配正则。 5、“location / {}”:所有location 都不能匹配后的默认匹配。