控制Nginx併發連線數量
ngx_http_limit_conn_module 這個模組是用於限制每個定義的key只的連線數,特別是單ip的連結數
用於定義key設定的最大連線數量,當超過設定的最大連線數時,伺服器會返回錯誤程式碼。
nginx的配置如下:
修改nignx配置檔案:
在http欄位中新增:limit_conn_zone $binary_remote_addr zone=addr:10m;
在server欄位location中新增:limit_conn addr 1; <<限制單ip的併發連線數為1
語法:limit_conn_zone key zone=name:size;
key 呢可以是字串,nginx自帶的變數$binary_remote_addr 和$server_name
語法:limit_conn zone number;
zone為上文中配置的zone區域,以及併發連線數
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 8990;
server_name www.ofo.com;
root /home/inca/www;
location / {
index index.html index.php index.htm;
limit_conn addr 1;
}
使用ab命令進行測試:
檢視服務端訪問日誌:
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
可以看出來狀態碼202和503都是1:1的出現。Nginx已經做出訪問的限制。
限制虛擬主機連線數:
不僅可以限制單ip的併發連線數。還可以限制虛擬主機的總連線數量,甚至可以對兩者同時限制。
http欄位上文資訊 ;
limit_conn_zone $server_name zone=perserver:10m;
server欄位下文資訊:
limit_conn perserver 2;·