Nginx限制某個IP同一時間段的串連次數和請求數,nginx同一時間

來源:互聯網
上載者:User

Nginx限制某個IP同一時間段的串連次數和請求數,nginx同一時間

nginx可以通過ngx_http_limit_conn_module和ngx_http_limit_req_module配置來限制ip在同一時間段的訪問次數.

ngx_http_limit_conn_module:該模組用於限制每個定義的密鑰的串連數,特別是單個IP地址的串連數.使用limit_conn_zone和limit_conn指令.

ngx_http_limit_req_module:用於限制每一個定義的密鑰的請求的處理速率,特別是從一個單一的IP地址的請求的處理速率。使用“泄漏桶”方法進行限制.指令:limit_req_zone和limit_req.

 

ngx_http_limit_conn_module:限制單個IP的串連數樣本

http {     limit_conn_zone $binary_remote_addr zone=addr:10m;        #定義一個名為addr的limit_req_zone用來儲存session,大小是10M記憶體,    #以$binary_remote_addr 為key,    #nginx 1.18以後用limit_conn_zone替換了limit_conn,    #且只能放在http{}程式碼片段.    ...     server {         ...         location /download/ {             limit_conn addr 1;   #串連數限制            #設定給定索引值的共用記憶體地區和允許的最大串連數。超出此限制時,伺服器將返回503(服務臨時不可用)錯誤.
       #如果地區儲存空間不足,伺服器將返回503(服務臨時不可用)錯誤
}

 

可能有幾個limit_conn指令,以下配置將限制每個用戶端IP與伺服器的串連數,同時限制與虛擬伺服器的總串連數

 

http {     limit_conn_zone $binary_remote_addr zone=perip:10m;     limit_conn_zone $server_name zone=perserver:10m     ...     server {         ...         limit_conn perip 10;       #單個用戶端ip與伺服器的串連數.        limit_conn perserver 100;  #限制與伺服器的總串連數        }

 

參考文檔:http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html

 

 

 ngx_http_limit_req_module:限制某一時間內,單一IP的請求數.樣本:

http {    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;    ...  #定義一個名為one的limit_req_zone用來儲存session,大小是10M記憶體,  

  #以$binary_remote_addr 為key,限制平均每秒的請求為1個,
  #1M能儲存16000個狀態,rete的值必須為整數,
  
server { ... location /search/ { limit_req zone=one burst=5;
        
        #限制每ip每秒不超過1個請求,漏桶數burst為5,也就是隊列.
        #nodelay,如果不設定該選項,嚴格使用平均速率限制請求數,超過的請求被延時處理.
        #舉個栗子:
        #設定rate=20r/s每秒請求數為20個,漏桶數burst為5個,
        #brust的意思就是,如果第1秒、2,3,4秒請求為19個,第5秒的請求為25個是被允許的,可以理解為20+5
        #但是如果你第1秒就25個請求,第2秒超過20的請求返回503錯誤.
        #如果地區儲存空間不足,伺服器將返回503(服務臨時不可用)錯誤 
        #速率在每秒請求中指定(r/s)。如果需要每秒少於一個請求的速率,則以每分鐘的請求(r/m)指定。 

        

}

 

還可以限制來自單個IP地址的請求的處理速率,同時限制虛擬伺服器的請求處理速率:

 

http {    limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;    limit_req_zone $server_name zone=perserver:10m rate=10r/s;    ...    server {        ...            limit_req zone=perip burst=5 nodelay;  #漏桶數為5個.也就是隊列數.nodelay:不啟用延遲.            limit_req zone=perserver burst=10;    #限制nginx的處理速率為每秒10個        }    

 

參考文檔:http://nginx.org/en/docs/http/ngx_http_limit_req_module.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.