In the http {} section,
is setmap $http_header_1 $route {default 10;}
map $http_header_2 $route {default 20;}
map $http_header_3 $route {default 30;}
The requested header is set to
curl -H "header_1:0" http://xxx.com/xxx
Then in the server {} section,
echo "$route";
The printed result is always 30, because the third map instruction overwrites the previous value;
The question is: How to get the desired value based on different headers in the map part?
To solve problem 1, the way I think is
map $http_header_1 $route1 {default 10;}
map $http_header_2 $route2 {default 20;}
map $http_header_3 $route3 {default 30;}
Then in the location {} section, use
if ($http_header_1) {
echo "$route1";
}
To get the desired value; Shamefully, this if seems to have failed, and nginx does not recommend using if
阿神2017-05-16 17:31:03
Okay, I’ve done it with if, but nginx doesn’t recommend using if. Does anyone have a better solution?
Thank you. However, your answer did not answer my question.
My business needs are:
map $http_header_1 $route {
default 110;
a 111;
b 112;
c 113;
}
map $http_header_2 $route {
default 210;
a 211;
b 212;
c 213;
}
map $http_header_3 $route {
default 310;
a 311;
b 312;
c 313;
}
That is, the request has and only one of $httpheader1, $httpheader2, $httpheader3, and has a corresponding value of one of a, b, and c.
nginx needs to determine the key of the header and return a confirmed $route value based on the value corresponding to the key.
最终$route为 111, 并 fastcgi_pass localhost:111
最终$route为 212, 并 fastcgi_pass localhost:212
最终$route为 313, 并 fastcgi_pass localhost:313
In the end, there are 9 business processes in total, each listening to a port.
漂亮男人2017-05-16 17:31:03
The host needs to understand a few things: 1. The statements in the map instruction must execute 1 of N by default.
map $http_header_1 $route {default 10;}
map $http_header_2 $route {default 20;}
map $http_header_3 $route {default 30;}
is equivalent to
传入$http_header_1任意值(即使为null),返回$route=10;
传入$http_header_2任意值(即使为null),返回$route=20;
传入$http_header_3任意值(即使为null),返回$route=30;
So, the final outgoing $route is 30;
map is an instruction to establish the mapping relationship between multiple incoming values and outgoing values. It is best that the incoming value has been defined and assigned before being passed to the map, otherwise default will be executed directly.
The original poster can give it a try
map $http_user_agent $route{
"Baiduspider" 1; #当$http_user_agent为Baiduspider,返回$route = 1
"Googlebot" 2; #当$http_user_agent为Googlebot,返回$route = 2
default 0; #否则,返回$route = 0
}