赞
踩
1.1.创建变量与赋值
set $hello "hello world";
1.2.Perl的变量插值
set $hello "hello world";
print "this is $hello .";
1.3.大括号插值
set $hello "hello";
print "this is ${hello}World .";
1.4.输出 $ 符
geo $dollar {
default "$";
}
server {
listen 8080;
location /test {
echo "This is a dollar sign: $dollar";
}
}
1.5.变量创建,赋值及作用域问题
set $hello "hello";
print "this is ${hello}World .";
如set指令中,nginx启动后是存在变量$hello的,但是只有真正运行到该地方时,变量才赋值了
例:
server {
listen 8080;
location /foo {
echo "foo = [$foo]";
}
location /bar {
set $foo 32;
echo "foo = [$foo]";
}
}
结果:
$ curl 'http://localhost:8080/foo'
foo = []
$ curl 'http://localhost:8080/bar'
foo = [32]
$ curl 'http://localhost:8080/foo'
foo = []
从这个例子我们可以看到,set 指令因为是在 location /bar 中使用的,所以赋值操作只会在访问 /bar 的请求中执行。而请求 /foo 接口时,我们总是得到空的 $foo 值,因为用户变量未赋值就输出的话,得到的便是空字符串。
server {
listen 8080;
location /foo {
set $a hello;
echo_exec /bar;
}
location /bar {
echo "a = [$a]";
}
}
结果
$ curl localhost:8080/foo
a = [hello]
$ curl localhost:8080/bar
a = []
这时候如果访问localhost:8080/foo,就会跳转到/bar,输出结果a = [hello],但是如果直接访问localhost:8080/bar,输出结果则为a = [],因为$a变量没有赋值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。