How to Configure Timeouts in Nginx for Better Performance
To configure timeouts in Nginx, use directives like
client_body_timeout, client_header_timeout, and keepalive_timeout inside the server or http block. These settings control how long Nginx waits for client data and keeps connections open before closing them.Syntax
Timeout directives in Nginx control how long the server waits for certain events before closing connections. They are set using the following syntax:
client_body_timeout time;- Wait time for client to send body data.client_header_timeout time;- Wait time for client to send header data.keepalive_timeout time [header_timeout];- Time to keep connections alive for reuse.send_timeout time;- Timeout for sending response to client.
Each time value is specified in seconds or with a time unit like s for seconds or m for minutes.
nginx
client_body_timeout 10s; client_header_timeout 10s; keepalive_timeout 75s 75s; send_timeout 10s;
Example
This example shows how to set timeouts in the http block of the Nginx configuration to control client connection behavior globally.
nginx
http {
client_body_timeout 12s;
client_header_timeout 12s;
keepalive_timeout 65s 65s;
send_timeout 15s;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}Output
Nginx starts with the configured timeouts active, closing connections if clients are idle longer than the set times.
Common Pitfalls
Common mistakes when configuring timeouts in Nginx include:
- Setting timeouts too low, causing premature connection closures and client errors.
- Setting timeouts too high, which can waste server resources by holding connections open unnecessarily.
- Placing timeout directives in the wrong context (e.g., inside
locationblocks where they are not supported). - Forgetting to reload or restart Nginx after changing configuration, so changes do not take effect.
nginx
## Wrong: timeout inside location block (ignored)
server {
listen 80;
location / {
client_body_timeout 5s; # This will be ignored
}
}
## Right: timeout inside http or server block
http {
client_body_timeout 5s;
}Quick Reference
| Directive | Purpose | Default Value | Context |
|---|---|---|---|
| client_body_timeout | Timeout for reading client request body | 60s | http, server |
| client_header_timeout | Timeout for reading client request header | 60s | http, server |
| keepalive_timeout | Timeout for keeping connections alive | 75s | http, server |
| send_timeout | Timeout for sending response to client | 60s | http, server |
Key Takeaways
Set timeout directives like
client_body_timeout and keepalive_timeout in the http or server block.Avoid setting timeouts too low or too high to balance resource use and client experience.
Timeout directives do not work inside location blocks; place them correctly.
Reload Nginx after changes to apply new timeout settings.
Use time units (s, m) for clarity and precision in timeout values.