2013-01-21 68 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