關於nginx的限速模組
nginx 使用 ngx_http_limit_req_module和ngx_http_limit_conn_module 來限制對資源的請求 這種方法,對於CC攻擊(Challenge Collapsar)or DDOS(分散式阻斷服務)有一定的用處 1、HttpLimitReqModule 限制request 事實上就是 the processing rate of requests coming from a single IP address,使用的是漏桶演算法(Leaky Bucket) Leaky Bucket有兩種處理方式,具體可以看wikiTraffic Shaping和Traffic Policing 在桶滿水之後,常見的兩種處理方式為: 1)暫時攔截住上方水的向下流動,等待桶中的一部分水漏走後,再允許存取上方水 2)溢出的上方水直接拋棄 將水看作網路通訊中資料包的抽象,則方式1起到的效果稱為Traffic Shaping,方式2起到的效果稱為Traffic Policing 由此可見,Traffic Shaping的核心理念是"等待",Traffic Policing的核心理念是"丟棄"。它們是兩種常見的流速控制方法 Syntax: limit_req zone=name [burst=number] [nodelay];Default: —Context: http, server, location 樣本
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;server { location /search/ { limit_req zone=one burst=5 nodelay; }
第一段配置 第一個參數:$binary_remote_addr 表示通過remote_addr這個標識來做限制,“binary_”的目的是縮寫記憶體佔用量,是限制同一用戶端ip地址 第二個參數:zone=one:10m表示產生一個大小為10M,名字為one的記憶體地區,用來儲存訪問的頻次資訊 第三個參數:rate=1r/s表示允許相同標識的用戶端的訪問頻次,這裡限制的是每秒1次,還可以有比如30r/m的 第二段配置 第一個參數:zone=one 設定使用哪個配置地區來做限制,與上面limit_req_zone 裡的name對應 第二個參數:burst=5,重點說明一下這個配置,burst爆發的意思,這個配置的意思是設定一個大小為5的緩衝區當有大量請求(爆發)過來時,超過了訪問頻次限制的請求可以先放到這個緩衝區內 第三個參數:nodelay,如果設定,超過訪問頻次而且緩衝區也滿了的時候就會直接返回503,如果沒有設定,則所有請求會等待排隊 下面這個配置可以限制特定UA(比如搜尋引擎)的訪問
limit_req_zone $anti_spider zone=one:10m rate=10r/s;limit_req zone=one burst=100 nodelay;if ($http_user_agent ~* "googlebot|bingbot|Feedfetcher-Google") { set $anti_spider $http_user_agent;}
2、ngx_http_limit_conn_module這個模組就是 limit the number of connections from a single IP address Not all connections are counted. A connection is counted only if it has a request processed by the server and the whole request header has already been read Syntax: limit_conn zone number;Default: —Context: http, server, location 樣本
http { limit_conn_zone $binary_remote_addr zone=addr:10m; ... server { ... location /download/ { limit_conn addr 1; #頻寬節流設定,對單個串連限數,如果一個ip兩個串連,就是500x2k limit_rate 100k; } }}
Sets the shared memory zone and the maximum allowed number of connections for a given key value. When this limit is exceeded, the server will return the 503 (Service Temporarily Unavailable) error in reply to a request $binary_remote_addr是限制同一用戶端ip地址$server是限制同一server最大並發數limit_conn為限制並發串連數,nginx 1.18以後用limit_conn_zone替換了limit_conn 配置完之後,我們可以使用ab或者webbench來測試一下 ab -n 5 -c 1 http://www.test.org/test.php 正常情況下可以這樣來配置
http { .. limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=2r/s; limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m; .. server { .. location / { limit_req zone=req_limit_per_ip burst=5 nodelay; limit_conn conn_limit_per_ip 30; } .. }}
參數根據具體配置了