Nginx map指令使用方法

Nginx map指令使用方法

  1. map指令由ngx_http_map_module模块提供,并且默认加载。
  2. map指令用来创建变量,仅在变量被接受的时候执行视图映射操作。
  3. map指令配置段位于http段内。
  4. map指令有三个参数:
    default:默认值,当没有设置 default,将会用一个空的字符串作为默认的结果。
    hostnames:允许用前缀或者后缀掩码指定域名作为源变量值。(这个参数必须写在值映射列表的最前面)
    include:包含一个或多个含有映射值的文件。
  5. 可以使用正则表达式:
    ~ 开头,表示这个正则表达式对大小写敏感。
    ~*开头,表示这个正则表达式对大小写不敏感。
  6. 使用示例

    http {
        map $http_user_agent $agent {
            ~curl curl;
            ~*chrome chrome;
        }
        server {
            listen       8080;
            server_name  www.test.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--linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
    agent: curl
  7. 使用实例
    维护一个ip.conf的配置文件,实现根据ip自动切换目录并且不用频繁重启nginx
    ip.conf实例内容如下

    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.test.com;
            root /data/$dir/www;
            rewrite ^/(js|images|css)/(.*) http://static.test.com/$1/$2 permanent;
            location / {
                 try_files $uri $uri/ /index.php?$query_string;
            }
        }
    }

下面关于Nginx的文章您也可能喜欢,不妨参考下:

Nginx 的详细介绍请点这里
Nginx 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2017-11/148332.htm