nginx.conf使用的是一種微型編程語言
set $a hello 設置變量(用戶自定義變量)
echo "$a"引用
location /test{
set $a hello;
echo "a=$a";
}
#curl http://localhost/test訪問test接口
echo_exec和rewrite 都可以進行內部跳轉
location /test {
set $var hello;
#echo_exec /next;
rewrite ^ /next;
}
location /next {
echo "${var} world!";
}
URL : http://www.baidu.com/news/8888
URI : /news/8888
nginx內建變量
$uri和$request_uri都是獲取請求的uri($uri經過解碼,不含參數。$request_uri未經解碼,含有參數)
location /test {
uri = $uri;
request_uri = $request_uri;
}
#curl http://localhost/test/hello%20world?a=3&b=4
uri = /test/hello world
request_uri = /test/hello%20world?a=3&b=4
另一種常見的內建變量爲:$arg_*(*爲任意字符,變量羣)如:$arg_name此變量的值是獲取當前請求名爲name的URI參數的值,未解碼
location /test{
#set_unescape_uri $name $arg_name;(可以使用set_unescape_uri配置指令進行解碼)
echo "name:$arg_name";
echo "age:$arg_age";
}
#curl "http://localhost/test?name=tom&age=20"
name:tom
age:20
許多內建變量都是隻讀的,如$uri,要絕對避免對其賦值,否則可能會導致nginx進程崩潰
$args獲取請求url的參數串(URL中?後邊的部分),可以被強行改寫
location /test{
set $orig_args $args; #用orig_args保存請求的原始的url參數
set $args "a=5&b=8"; #將url參數強行改寫
echo "orig_args:$orig_$args";
echo "args:$args";
}
#curl http://localhost/test?a=1&b=1&c=1
orig_args:a=1&b=1&c=1
args:a=5&b=8
讀取$args時,nginx會執行一小段代碼,從nginx核心中專門存放當前URL參數串的位置去讀取數據;
改寫$args時,nginx會執行另一小段代碼,對此位置進行改寫。
在讀取變量是執行的這段特殊代碼,在nginx中被稱爲“取處理程序”;改寫變量時執行的這段特殊代碼,被稱爲“存處理程序”
nginx不會事先解析好URL參數串,而是在用戶讀取某個$arg_XXX變量時,調用“取處理程序”去掃描URL參數串。
ngx_map和ngx_geo等模塊(配置指令map和geo)使用了變量值的緩存機制
請求分爲 主請求和子請求。主請求:如http客戶端發起的外部請求。子請求:有nginx正在處理的請求在nginx內部發起的一種級聯請求(抽象調用)。
ngx_echo模塊的echo_location指令可以發起到其它接口的GET類型的“子請求”
location /main{
echo_location /test1;
echo_location /test2;
}
location /test1{
echo test1;
}
location /test2{
echo test2;
}
#curl http://localhost/main
test1
test2
即便是父子請求之間,同名變量一般不會互相干擾
ngx_echo,ngx_lua,ngx_srcache等許多第三方模塊都禁用父子請求間的變量共享。ngx_auth_request不同
location /test {
echo "name:[$arg_name]";
}
#curl http://localhost/test
name:[]
#curl http://localhost/test?name=
name:[]
變量值找不到和空字符 可以通過添加一段lua代碼區分
location /test {
content_by_lua '
if ngx.var.arg_name == nil then
ngx.say("name:not found")
else
ngx.say(", name: [", ngx.var.arg_name,"]")
end
';
}
#curl http://localhost/test
name:not found
#curl http://localhost/test?name=
name:[]