首頁  >  問答  >  主體

nginx conf 的設定問題

1

在 http {} 部分, 設定了

map $http_header_1 $route {default 10;}
map $http_header_2 $route {default 20;}
map $http_header_3 $route {default 30;}

請求的header設定為

curl -H "header_1:0" http://xxx.com/xxx

然後在 server {} 部分,

echo "$route";

列印結果總是 30, 因為 第三個map指令覆寫了前面的值;

問題來了: 如何在map部分根據不同的header, 得到想要的值?

2

為解決問題1, 我想的辦法為

map $http_header_1 $route1 {default 10;}
map $http_header_2 $route2 {default 20;}
map $http_header_3 $route3 {default 30;}

然後在 location {} 部分, 用

if ($http_header_1) {
echo "$route1";
}

去得到想要的值; 可恥的是, 這個 if 似乎沒成功, 而且nginx不建議使用if


那麼, 哪位深藏功與名的同學, 幫忙解答一下?

PHP中文网PHP中文网2688 天前600

全部回覆(2)我來回復

  • 阿神

    阿神2017-05-16 17:31:03

    好吧, 用if搞定了, 可是nginx不推薦使用if, 哪位同學有更好的方案?


    @冰紛 那位, 似乎回覆您的文字不能使用md格式, 我在這裡回覆您一下:

    感謝. 不過您的答案, 沒有回答我的問題.

    我的業務需求是:

    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;
    }
    

    也即, request帶有且只帶有$httpheader1,$httpheader2,$httpheader3 的其中一個, 並有相應的值為a,b,c 的其中一個.

    nginx需要根據判斷該頭的key, 並根據key對應的value返回一個確認的 $route 值.

    業務範例:

    1. curl -H "header_php:a" http://biz.domain.com/ 最终$route为 111, 并 fastcgi_pass localhost:111
    2. curl -H "header_python:b" http://biz.domain.com/ 最终$route为 212, 并 fastcgi_pass localhost:212
    3. curl -H "header_ruby:c" http://biz.domain.com/ 最终$route为 313, 并 fastcgi_pass localhost:313

    然後

    1. php-1監聽111, php-2監聽112, php-3監聽113
    2. python-1監聽211, python-2監聽212, python-3監聽213
    3. ruby-1監聽311, ruby​​-2監聽312, ruby​​-3監聽313

    最終一共有9個業務進程, 各自監聽一個端口.

    不要問我為什麼會有這種奇葩需求, 深藏功與名啊~~~


    所以, 您的答案, 不能滿足我的獸欲啊

    回覆
    0
  • 漂亮男人

    漂亮男人2017-05-16 17:31:03

    樓主需要明白幾處: 1. map指令內的語句是預設必然執行1 of N的。

    map $http_header_1 $route {default 10;}
    map $http_header_2 $route {default 20;}
    map $http_header_3 $route {default 30;}
    

    就相當於

    传入$http_header_1任意值(即使为null),返回$route=10;
    传入$http_header_2任意值(即使为null),返回$route=20;
    传入$http_header_3任意值(即使为null),返回$route=30;
    

    所以,最後傳出的$route為30;

    map是組成多個傳入值與傳出值映射關係的指令,這個傳入值最好在傳入到map前已經被定義、賦值了,不然就直接執行default。

    樓主可以試試

        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
        }
    

    回覆
    0
  • 取消回覆