插件窝 干货文章 Nginx 请求超时的实现

Nginx 请求超时的实现

超时 timeout 请求 默认 441    来源:    2025-04-01

Nginx 请求超时配置详解

作为IT工程师,我来详细介绍Nginx中实现请求超时的各种配置方法。

主要超时配置参数

1. 客户端请求超时

http {
    # 客户端请求头读取超时时间(默认60s)
    client_header_timeout 30s;

    # 客户端请求体读取超时时间(默认60s)
    client_body_timeout 30s;

    # 客户端保持连接的超时时间(默认75s)
    keepalive_timeout 65s;

    # 发送响应给客户端的超时时间(默认60s)
    send_timeout 60s;
}

2. 代理服务器超时

location / {
    # 与上游服务器建立连接的超时时间(默认60s)
    proxy_connect_timeout 30s;

    # 从上游服务器读取响应的超时时间(默认60s)
    proxy_read_timeout 60s;

    # 发送请求到上游服务器的超时时间(默认60s)
    proxy_send_timeout 60s;
}

3. FastCGI超时

location ~ \.php$ {
    # FastCGI连接超时(默认60s)
    fastcgi_connect_timeout 30s;

    # FastCGI读取响应超时(默认60s)
    fastcgi_read_timeout 60s;

    # FastCGI发送请求超时(默认60s)
    fastcgi_send_timeout 60s;
}

高级超时配置

1. 长轮询应用配置

location /long-polling {
    proxy_read_timeout 300s;  # 5分钟超时
    proxy_send_timeout 300s;
}

2. 上传大文件配置

server {
    client_max_body_size 100M;  # 最大上传文件大小
    client_body_timeout 300s;   # 上传超时时间
}

3. WebSocket连接超时

location /wsapp/ {
    proxy_pass http://wsbackend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400s;  # WebSocket保持24小时
}

最佳实践建议

  1. 生产环境推荐值

    • 普通HTTP请求:30-60秒
    • API请求:5-30秒
    • 文件上传:根据文件大小调整
  2. 监控与调优

    log_format timed_combined '$remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" '
                           '$request_time $upstream_response_time';
    
  3. 动态调整

    # 根据请求URI设置不同超时
    location /api/ {
       proxy_read_timeout 30s;
    }
    
    location /reports/ {
       proxy_read_timeout 300s;
    }
    

通过合理配置这些超时参数,可以有效防止资源被长时间占用,提高服务器稳定性和用户体验。