Nginx 持续连接超时时间
2013-06-04 by dongnan
开始之前
Nginx 默认支持 HTTP协议的 keep-alive持续连接(长连接)功能,其默认的超时时间为75秒,
在此期间内后续的http请求可以复用已建立的TCP连接,从而节省新建TCP连接握手的时间。
但是就像所有事物都有两面性,keep-alive在某些场景也会有不足的方面,
比如就算是在空闲状态它还是会消耗服务器资源,所以你可以根据自己的实际需求调整 keep-alive的超时时间,例如将 keep-alive 超时时间调整为30秒。
nginx默认返回的响应头信息:
curl -IL http://zongming.net/404.html
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 19 Mar 2013 09:40:24 GMT
Content-Type: text/html; charset=utf8
Content-Length: 211
Last-Modified: Sun, 17 Feb 2013 07:44:39 GMT
Connection: keep-alive
Accept-Ranges: bytes
测试
编辑 nginx.conf 配置文件,设置 keepalive_timeout 两个参数值为 30:
grep 'keepalive_timeout' /etc/nginx/nginx.conf
keepalive_timeout 30 30;
重启nginx进程:
nginx -t && nginx reload
验证
curl -IL http://zongming.net/404.html
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 19 Mar 2013 09:42:16 GMT
Content-Type: text/html; charset=utf8
Content-Length: 211
Last-Modified: Sun, 17 Feb 2013 07:44:39 GMT
Connection: keep-alive
Keep-Alive: timeout=30
Accept-Ranges: bytes
这次HTTP响应头多了一个 Keep-Alive字段用于输出 keep-alive 超时信息。
keepalive_timeout 指令
语法: keepalive_timeout timeout [header_timeout]
默认值: keepalive_timeout 75s;
使用字段: http, server, location
参数:
参数1指定了客户端与服务器 keep-alive的超时时间,值为0将禁用 keep-alive功能。
参数2(可选)在HTTP响应头"Keep-Alive: timeout=time"字段中设置一个值。这两个参数值可以不相同。