你可以做一个小动作。如果必须可以从一个http
块中的每个server
块访问此值,则可以使用map
指令。这将如何工作?
map
指令允许您在http
块中的任何位置使用变量,该值将根据某个映射键计算。说得通的例子:
http {
...
/*
value for your $my_everywhere_used_variable will be calculated
each time when you use it and it will be based on the value of $query_string.
*/
map $query_string $my_everywhere_used_variable {
/*
if the actual value of $query_string exactly match this below then
$my_everywhere_used_variable will have a value of 3
*/
/x=1&y=2&opr=plus 3;
/*
if the actual value of $query_string exactly match this below then
$my_everywhere_used_variable will have a value of 4
*/
/x=1&y=4&opr=multi 4;
/*
it needs to be said that $my_everywhere_used_variable's value is calculated each
time you use it. When you use it as pattern in a map directive (here we used the
$query_string variable) some variable which will occasionally change
(for example $args) you can get more flexible values based on specific conditions
*/
}
// now in server you can use this variable as you want, for example:
server {
location/{
rewrite .* /location_number/$my_everywhere_used_variable;
/*
the value to set here as $my_everywhere_used_variable will be
calculated from the map directive based on $query_string value
*/
}
}
}
所以,现在,这对你意味着什么?使用这个简单的技巧,您可以使用map
指令为所有server
块设置一个全局变量。您可以使用default
关键字为您的地图值设置默认值。正如在这个简单的例子:
map $host $my_variable {
default lalalala;
}
在这个例子中,我们计算的$my_variable
对$host
值的值,但实际上它并不重要$host
是什么,因为我们将始终设置lalalala作为价值我们的变量默认和没有其他选项。现在,在你的代码随处可见时,你会以同样的方式使用$my_variable
所有其他可用变量(例如与set
指令创建),你会得到lalalala
的价值为什么是这个比单纯使用set
指令更好?由于set
指令(如doc所示,nginx set directive仅在server, location and if
块内可访问,所以它不能用于为多个server
块创建全局变量。
文档约map
指令都可以在这里:map directive
在任何服务器中设置{}块被继承。 –
你是说如果我在第一个服务器中定义一个var,那么我可以在它下面的所有服务器块中使用它? – sinory