map指令由ngx_http_map_module模塊提供,并且默認(rèn)加載。
map指令用來(lái)創(chuàng)建變量,僅在變量被接受的時(shí)候執(zhí)行視圖映射操作。
map指令配置段位于http段內(nèi)。
map指令有三個(gè)參數(shù):
default:默認(rèn)值,當(dāng)沒(méi)有設(shè)置 default,將會(huì)用一個(gè)空的字符串作為默認(rèn)的結(jié)果。
hostnames:允許用前綴或者后綴掩碼指定域名作為源變量值。(這個(gè)參數(shù)必須寫(xiě)在值映射列表的最前面)
include:包含一個(gè)或多個(gè)含有映射值的文件。
可以使用正則表達(dá)式:
以 ~ 開(kāi)頭,表示這個(gè)正則表達(dá)式對(duì)大小寫(xiě)敏感。
以 ~*開(kāi)頭,表示這個(gè)正則表達(dá)式對(duì)大小寫(xiě)不敏感。
使用示例
http {
map $http_user_agent $agent {
~curl curl;
~*chrome chrome;
}
server {
listen 8080;
server_name www.tjdsmy.cn;
location /hello {
default_type text/plain;
echo http_user_agent: $http_user_agent;
echo agent: agent:$agent;
}
}
}
執(zhí)行curl 127.0.0.1:8080/hello得到如下信息
http_user_agent: curl/7.15.5 (x86_64-RedHat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
agent: curl
使用實(shí)例
維護(hù)一個(gè)ip.conf的配置文件,實(shí)現(xiàn)根據(jù)ip自動(dòng)切換目錄并且不用頻繁重啟nginx
ip.conf實(shí)例內(nèi)容如下
192.168.1.1 dir1;
192.168.1.2 dir2;
nginx配置如下
http {
map $ip $dir {
default test;
include ip.conf;
}
server {
listen 8080;
server_name www.tjdsmy.cn;
root /data/$dir/www;
rewrite ^/(js|images|css)/(.*) http://www.tjdsmy.cn/$1/$2 permanent;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
}
}