til icon indicating copy to clipboard operation
til copied to clipboard

nginx - map/set variable vs if multi condition

Open xluffy opened this issue 3 years ago • 0 comments

Nginx không hỗ trợ kiểm tra nhiều điều kiện đồng thời hoặc nested giống các ngôn ngữ lập trình. Ví dụ:

if ($uri = 'ping' && $request_method = 'GET) {
  do_something
}
if ($uri = 'ping') {
  if($request_method = 'GET) {
    do_something
  }
}

Nhưng có thể trick bằng cách như sau

   set $by_pass_auth "";

   if ($uri = ping){
      set $by_pass_auth T;
   }

   if ($request_method = 'GET'){
      set $by_pass_auth "${by_pass_auth}r";
   }

   if ($UD = Tr){
    do_something
   }

Hoặc nếu cần kiểm tra nhiều điều kiện OR, ví dụ nếu:

  • Client IP thuộc 1 danh sách nào đó hoặc
  • User-gent thuộc một danh sách nào đó hoặc
  • URI thuộc một danh sách nào đó

Có thể làm như sau:

map "$remote_addr:$http_user_agent:$uri" $whitelist {
  default 0;
  "~*(13.125.62.245)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
  "~*(13.209.181.226)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
  "~*(14.161.25.219)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
  "~*(13.125.62.245)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
  "~*(118.69.77.83)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
  "~*(34.209.144.109)|(zencoder)|(pollfish_rewards)|(appodeal_rewards)" 1;
}

server {
  ...
  set $auth_type "off";

  if ($whitelist = 0) {
    set $auth_type "Roswell near area 51";
  }

  auth_basic $auth_type;
  auth_basic_user_file /etc/nginx/security.d/htpasswd.conf;

  ...
}

http://nginx.org/en/docs/http/ngx_http_map_module.html http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#set

xluffy avatar Jun 03 '21 14:06 xluffy