首頁 > 運維 > Nginx > 主體

nginx如何設定目錄白名單和ip白名單

PHPz
發布: 2023-05-18 15:52:46
轉載
1760 人瀏覽過

1.設定目錄白名單:對指定請求路徑不設定限制,如對請求路徑為api目錄下的請求不做限制,則可寫為

server{
    location /app {
      proxy_pass http://192.168.1.111:8095/app;

      limit_conn conn 20;

      limit_rate 500k;

      limit_req zone=foo burst=5 nodelay; 
    }
    location /app/api {
      proxy_pass http://192.168.1.111:8095/app/api
    }
}
# 因nginx会优先进行精准匹配,所以以上写法即接触了对api目录下属路径的限制
登入後複製

2.設定ip白名單,需用到nginx geo 與nginx map

#在沒有人為刪除的情況下(--without-http_geo_module或--without-http_map_module),nginx預設載入了ngx-http-geo-module和ngx-http-map-module相關內容;

ngx-http-geo-module可以用來建立變量,變數值依賴客戶端ip 位址;

ngx-http-map-module可以基於其他變數及變數值進行變數創建,其允許分類,或映射多個變數到不同值並儲存在一個變數中;

nginx geo 格式说明
 
syntax ( 语法格式 ): geo [$address] $variable { ... }
default ( 默认 ): -
content ( 配置段位 ): http
nginx map 格式说明
syntax ( 语法格式 ): map string $variable { ... }
default ( 默认 ):-
content ( 配置段位 ): http
 
白名单配置示例
 
http{
   # ... 其他配置内容
   #定义白名单ip列表变量
   geo $whiteiplist {
     default 1 ;
     127.0.0.1/32 0;
     64.223.160.0/19 0;
   }
   #使用map指令映射将白名单列表中客户端请求ip为空串
   map $whiteiplist $limit{
     1 $binary_remote_addr ;
     0 "";
   }
   #配置请求限制内容
   limit_conn_zone $limit zone=conn:10m;
   limit_req_zone $limit zone=allips:10m rate=20r/s;
   server{
     location /yourapplicationname {
       proxy_pass http://192.168.1.111:8095/app;
       limit_conn conn 50;
       limit_rate 500k;
       limit_req zone=allips burst=5 nodelay;
     }
   }
}
白名单配置可用于对合作客户,搜索引擎等请求过滤限制
 
#(特殊情况处理)
 
#如果想仅限制指定的请求,如:只限制post请求,则:
http{
   # 其他请求..
   #请求地址map映射
   map $request_method $limit {
     default "";
     post $binary_remote_addr;
   }
   #限制定义
   limit_req_zone $limit zone=reqlimit:20m rate=10r/s;
   server{
     ... #与普通限制一致
   }
}
#在此基础上,想进行指定方法的白名单限制处理,则:
http{
   #...
   #定义白名单列表
   map $whiteiplist $limitips{
     1 $binary_remote_addr;
     0 "";
   }
 
   #基于白名单列表,定义指定方法请求限制
   map $request_method $limit {
     default "";
     # post $binary_remote_addr;
     post $limitips;
   }
 
   #对请求进行引用
   limit_req_zone $limit zone=reqlimit:20m rate=10r/s;
 
   #在server中进行引用
   server{
     #... 与普通限制相同
   }
}
登入後複製

以上是nginx如何設定目錄白名單和ip白名單的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!