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:[]