nginx中break和last的区别
一、环境准备
资源文件创建
mkdir -p /opt/tmp/wqy/test/aaa
mkdir -p /opt/tmp/wqy/test/bbb
echo "aaa" >> /opt/tmp/wqy/test/aaa/index.html
echo "bbb" >> /opt/tmp/wqy/test/bbb/index.html
二、测试过程
2.1、初始配置时
nginx配置
server {
listen 80;
server_name wqy.test.com;
access_log logs/wqy-test-com/access.log;
location ^~ /aaa {
root /opt/tmp/wqy/test;
}
location ^~ /bbb {
return 200 "hello world\n";
}
}
测试结果
#curl -s http://wqy.test.com/aaa/index.html -x 127.0.0.1:80
aaa
#curl -s http://wqy.test.com/bbb/index.html -x 127.0.0.1:80
hello world
2.2、配置rewrite last时
nginx配置
server {
listen 80;
server_name wqy.test.com;
access_log logs/wqy-test-com/access.log;
location ^~ /aaa {
rewrite ^/aaa/(.*) /bbb/$1 last;
root /opt/tmp/wqy/test;
}
location ^~ /bbb {
return 200 "hello world\n";
}
}
测试结果
#curl -s http://wqy.test.com/aaa/index.html -x 127.0.0.1:80
hello world
#curl -s http://wqy.test.com/bbb/index.html -x 127.0.0.1:80
hello world
url由重写前的
http://wqy.test.com/aaa/index.html
变为http://wqy.test.com/bbb/index.html
,重新进行location匹配后,匹配到第二个location条件,所以请求url得到的响应是hello wold
测试结论
配置rewrite last
时,请求跳出当前location,进入server块,重新进行location匹配,超过10次匹配不到报500错误。客户端的url不变
2.3、配置rewrite break时
nginx配置
server {
listen 80;
server_name wqy.test.com;
access_log logs/wqy-test-com/access.log;
location ^~ /aaa {
rewrite ^/aaa/(.*) /bbb/$1 break;
root /opt/tmp/wqy/test;
}
location ^~ /bbb {
return 200 "hello world\n";
}
}
测试结果
#curl -s http://wqy.test.com/aaa/index.html -x 127.0.0.1:80
bbb
#curl -s http://wqy.test.com/bbb/index.html -x 127.0.0.1:80
hello world
url由重写前的
http://wqy.test.com/aaa/index.html
变为http://wqy.test.com/bbb/index.html
,nginx按照重写后的url进行资源匹配,匹配到的资源文件是/opt/tmp/wqy/test/bbb/index.html
,所以请求url得到的响应就是/opt/tmp/wqy/test/bbb/index.html
文件中的内容:bbb
。
测试结论
配置rewrite break
时,请求不会跳出当前location,但资源匹配会按照重写后的url进行,如果location里面配置的是proxy_pass到后端,后端服务器收到的请求url也会是重写后的url。客户端的url不变。