How to Set keepalive_timeout in Nginx for Connection Management
Set the
keepalive_timeout directive inside the http, server, or location block in your Nginx configuration file to specify how long a connection should stay open. For example, keepalive_timeout 65; sets the timeout to 65 seconds. After changing it, reload Nginx to apply the new setting.Syntax
The keepalive_timeout directive controls how long an idle keep-alive connection stays open between the client and server. It accepts one or two time values. The first value sets the timeout for the client connection, and the optional second value sets the timeout for the response header.
- keepalive_timeout: The directive name.
- timeout: Time in seconds or with units (e.g., 65 or 65s) for how long to keep the connection alive.
- header_timeout (optional): Time for the response header timeout.
This directive can be placed inside http, server, or location blocks.
nginx
keepalive_timeout timeout [header_timeout];
Example
This example sets the keepalive timeout to 75 seconds for client connections and 75 seconds for response headers inside the http block. It helps keep connections open longer to improve performance for clients making multiple requests.
nginx
http {
keepalive_timeout 75s 75s;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}Output
Nginx configuration loaded successfully with keepalive_timeout set to 75 seconds.
Common Pitfalls
Common mistakes when setting keepalive_timeout include:
- Setting the timeout too high, which can keep connections open unnecessarily and waste server resources.
- Setting the timeout too low, causing clients to reconnect frequently and reducing performance benefits.
- Placing the directive in the wrong context, such as outside
http,server, orlocationblocks, which causes Nginx to ignore it.
Always reload Nginx after changes to apply the new settings.
nginx
## Wrong placement example (ignored by Nginx): keepalive_timeout 30; ## Correct placement example: http { keepalive_timeout 30; }
Quick Reference
| Directive | Description | Default Value | Context |
|---|---|---|---|
| keepalive_timeout | Sets timeout for keep-alive connections | 75s | http, server, location |
| timeout | Time to keep connection alive | N/A | N/A |
| header_timeout | Optional timeout for response header | Same as timeout if omitted | N/A |
Key Takeaways
Set keepalive_timeout inside http, server, or location blocks in nginx.conf.
Use a balanced timeout value to optimize resource use and client performance.
Reload Nginx after changing keepalive_timeout to apply the new setting.
Avoid placing keepalive_timeout outside valid contexts to ensure it works.
You can specify two time values: one for client timeout and one for header timeout.