nginx location and proxy_pass

Nginxlocation的格式为

location [=|~|~*|^~] uri { … }

Nginx匹配location时,有一定的优先级,=优先级最高,其次^~,最后是~~*。同一类型的匹配按照出现的先后顺序匹配。

下面是一个例子,来自http://wiki.nginx.org/HttpCoreModule#location

location  = / {
    # matches the query / only.
    [ configuration A ]
}
location  / {
    # matches any query, since all queries begin with /, but regular
    # expressions and any longer conventional blocks will be
    # matched first.
    [ configuration B ]
}
location ^~ /images/ {
    # matches any query beginning with /images/ and halts searching,
    # so regular expressions will not be checked.
    [ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
    # matches any request ending in gif, jpg, or jpeg. However, all
    # requests to the /images/ directory will be handled by
    # Configuration C.
    [ configuration D ]
}

不同请求的结果如下:

=^~都算字符常量匹配,而~~*算正则匹配。这个在下面的proxy_pass需要用到。

proxy_pass的格式为:

location match {
    proxy_pass target
}

proxy_pass的参数target由两部分组成,服务器地址和路径。如:

location的参数match为需要匹配到路径,它将一个URL分成了两部分,一部分是需要匹配的match,还有是剩下的left。如

location ~ /search {}

分别用不同的URL去匹配,得到的结果是

当将这两个结合在一起跳转时,跳转的地址为:

下面是一个最普通的例子:

location /a {
    proxy_pass http://cc;
}

location /b {
    proxy_pass http://cc/;
}

location /c/ {
    proxy_pass http://cc;
}

location  /d/ {
    proxy_pass   http://cc/;
}

分别用不同的URL去请求,跳转地址为: