一、環境准備
資源文件創建
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不變。