2013-01-21 69 views
20

如何在nginx conf文件中定义一个全局变量,在http块中定义一个全局变量,并且下面的所有服务器和位置都可以使用它。如何在nginx conf文件中定义一个全局变量

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 
     } 
    } 
+0

在任何服务器中设置{}块被继承。 –

+0

你是说如果我在第一个服务器中定义一个var,那么我可以在它下面的所有服务器块中使用它? – sinory

回答

58

你可以做一个小动作。如果必须可以从一个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

+0

不错! 我可以使用map指令覆盖全局变量吗? – confiq

+13

这个答案仍然不被接受? –

+0

任何想法如何在Lua块中访问$ my_everywhere_used_variable? – Sreeraj