你可以做一個小動作。如果必須可以從一個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