歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 關於nginx的限速模塊

關於nginx的限速模塊

日期:2017/3/1 12:21:11   编辑:關於Linux
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有兩種處理方式,具體可以看wiki Traffic 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;
        }

        ..
    }
}

參數根據具體配置了
Copyright © Linux教程網 All Rights Reserved