在一般狀況下,使用 nginx 基於 ip 限制訪問請求頻率等限制內容,咱們會須要對特定ip進行限制排除操做,所以本文引入了基於nginx geo 與 nginx map 進行此類情景相關配置;html
在沒有人爲操做刪除的狀況下(without-http_geo_module),nginx默認模塊中已經加載了ngx-http-geo-module相關內容;node
ngx-http-geo-module能夠用來建立變量,變量值依賴於客戶端 ip 地址;nginx
ngx-http-map-module能夠基於其餘變量及變量值進行變量建立,其容許分類,或者映射多個變量到不一樣值並存儲在一個變量中;api
ngx-http-map-module相關內容一樣在默認nginx中已存在,除非由人爲移除( --without-http_map_module)app
Nginx geo 格式說明搜索引擎
Syntax ( 語法格式 ): geo [$address] $variable { ... } Default ( 默認 ): - Content ( 配置段位 ): http
Nginx map 格式說明spa
Syntax ( 語法格式 ): map String $variable { ... } Default ( 默認 ):- Content ( 配置段位 ): http
http{ # ... 其餘配置內容 #定義白名單ip列表變量 geo $whiteiplist { default 1 ; #myself 127.0.0.1/32 0; #remote ip 64.223.160.0/19 0; } #使用map指令映射將白名單列表中客戶端請求ip爲空串 map $whiteiplist $limit{ 1 $binary_remote_addr ; 0 ""; } #配置請求限制內容 limit_req_zone $limit zone=foo:1m rate=10r/m; } server{ location /yourApplicationName { proxy_pass http://192.168.1.111:8095/app; # 在 server 中進行限制配置引用 zone = foo limit_req zone=foo burst=5 nodelay; } }
白名單配置可用於對合做客戶,搜索引擎等請求過濾限制code
#(特殊狀況處理) #若是想僅限制指定的請求,如:只限制Post請求,則: http{ # 其餘請求.. #請求地址map映射 map $request_method $limit { default ""; POST $binary_remote_addr; } #限制定義 limit_req_zone $limit zone=reqlimit:20m rate=10r/s; } #而後在server中進行引用。 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{ #... 與普通限制相同 } # 對應用中指定請求路徑不設置限制,如對請求路徑爲 即api目錄下的請求不作 # 限制,則可寫爲 server{ location /app { proxy_pass http://192.168.1.111:8095/app; limit_req zone=foo burst=5 nodelay; } location /app/api { proxy_pass http://192.168.1.111:8095/app/api } } # 因nginx會優先進行精準匹配,因此以上寫法即接觸了對api目錄下屬路徑的限制
參考官方文檔: server