如何在nginx conf文件中定义全局变量,如何在http块中定义全局变量,下面的所有服务器和位置都可以使用它。
http{
some confs
...
//define a global var mabe like
set APP_ROOT /home/admin
// and it can be use in all servers and locations below, like
server {
root $APP_ROOT/test1
}
server {
root $APP_ROOT/test2
}
}
最佳答案
您可以做点小技巧。如果必须从一个server
块中的每个http
块访问此值,则可以使用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 值设置默认值。如以下简单示例所示:map $host $my_variable {
default lalalala;
}
在此示例中,我们根据
$my_variable
值计算$host
的值,但是实际上$host
是什么都没有关系,因为默认情况下我们始终将lalalala设置为变量的值,并且没有其他选项。现在,在代码的所有位置,您将以与所有其他可用变量相同的方式使用$my_variable
(例如,使用set
指令创建),您将获得lalalala的值为什么这比仅使用
set
指令更好呢?正如doc所说,因为set
指令只能在server, location and if
块内部访问nginx set directive,所以它不能用于为许多server
块创建全局变量。有关
map
指令的文档可在此处获得:map directive