map $http_user_agent $agent { default ""; ~curl curl; ~*apachebench" ab;}正则表达式里可以包含命名捕获和位置捕获,这些变量可以跟结果变量一起被其它指令使用。
map $uri $value { /ttlsa_com /index.php; ~^/ttlsa_com/(?[warning]不能在map块里面引用命名捕获或位置捕获变量。如~^/ttlsa_com/(.*) /boy/$1; 这样会报错nginx: [emerg] unknown variable。[/warning]如果源变量值包含特殊字符如‘~’,则要以‘\’来转义。.*)$ /boy/; ~/fz(/.*) /index.php?; }
map $http_referer $value { Mozilla 111; \~Mozilla 222;}结果变量可以是一个字符串也可以是另外一个变量。
map $num $limit { 1 $binary_remote_addr; 0 "";}map指令有三个参数: default : 指定如果没有匹配结果将使用的默认值。当没有设置 default,将会用一个空的字符串作为默认的结果。 hostnames : 允许用前缀或者后缀掩码指定域名作为源变量值。这个参数必须写在值映射列表的最前面。 include : 包含一个或多个含有映射值的文件。 如果匹配到多个特定的变量,如掩码和正则同时匹配,那么会按照下面的顺序进行选择: 1. 没有掩码的字符串 2. 最长的带前缀的字符串,例如: “*.example.com” 3. 最长的带后缀的字符串,例如:“mail.*” 4. 按顺序第一个先匹配的正则表达式 (在配置文件中体现的顺序) 5. 默认值 map_hash_bucket_size 语法: map_hash_bucket_size size; 默认值: map_hash_bucket_size 32|64|128; 配置段: http 指定一个映射表中的变量在哈希表中的最大值,这个值取决于处理器的缓存。 map_hash_max_size 语法: map_hash_max_size size; 默认值: map_hash_max_size 2048; 配置段: http 设置映射表对应的哈希表的最大值。 二. 实例
http { map $http_user_agent $agent { ~curl curl; ~*chrome chrome; } server { listen 8080; server_name test.ttlsa.com; location /hello { default_type text/plain; echo http_user_agent: $http_user_agent; echo agent: agent:$agent; } }}# 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.5agent: curl
http { map $uri $match { ~^/hello/(.*) http://www.ttlsa.com/; } server { listen 8080; server_name test.ttlsa.com; location /hello { default_type text/plain; echo uri: $uri; echo match: $match; echo capture: $1; echo new: $match$1; } }}如需转载请注明出处:http://www.ttlsa.com/html/3206.html