Nginx 使用多个map条件语句(conditionally block)

在Nginx 的location中,if is evil.

因此多个if条件语句可以转化为多个map条件语句.

一般有两种方式,一个是map中直接map 两个变量,变量之间用:间隔;另外一个就是使用多个map,后一个map里面直接使用前面一个map里的变量,形成map chain. 下面详细说明:

第一种方式:

map "$http_x_target:$arg_target" $destination {
default upstream0;
~something upstream1;
~something2 upstream1;
~something3 upstream2;
}
...
server {
location / {
proxy_pass https://$destination;
}
}

第二种方式:

map $arg_target $arg_destination {
default upstream0;
something upstream1;
something2 upstream1;
something3 upstream2;
}
map $http_x_target $destination {
default $arg_destination;
something upstream1;
something2 upstream1;
something3 upstream2;
}
...
server {
location / {
proxy_pass https://$destination;
}
}

参考文档:

https://stackoverflow.com/questions/59671623/conditionally-map-values-in-nginx-config
https://gock.net/blog/2020/nginx-conditional-logging-responses/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.