How to Use proxy_buffering in Nginx for Efficient Proxying
Use the
proxy_buffering directive inside an Nginx location or server block to enable or disable buffering of responses from proxied servers. Setting proxy_buffering on; buffers responses before sending them to clients, improving performance and reducing load on backend servers.Syntax
The proxy_buffering directive controls whether Nginx buffers responses from proxied servers before sending them to clients.
It accepts two values:
on: Enables buffering (default).off: Disables buffering, sending data immediately.
This directive is placed inside http, server, or location blocks.
nginx
proxy_buffering on; # or proxy_buffering off;
Example
This example shows how to enable proxy buffering in a location that proxies requests to a backend server. Buffering helps improve client response times and reduces load on the backend.
nginx
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://backend_server;
proxy_buffering on;
proxy_buffers 8 16k;
proxy_buffer_size 16k;
}
}Common Pitfalls
Common mistakes when using proxy_buffering include:
- Disabling buffering (
proxy_buffering off;) without a reason, which can increase load on backend servers and reduce performance. - Not configuring
proxy_buffersandproxy_buffer_sizeproperly, leading to inefficient memory use or slow responses. - Placing
proxy_bufferingoutside ofhttp,server, orlocationblocks, which causes configuration errors.
Example of wrong and right usage:
nginx
# Wrong: disabling buffering without need
location /api/ {
proxy_pass http://backend_server;
proxy_buffering off;
}
# Right: enabling buffering with buffer sizes
location /api/ {
proxy_pass http://backend_server;
proxy_buffering on;
proxy_buffers 8 16k;
proxy_buffer_size 16k;
}Quick Reference
| Directive | Description | Default Value |
|---|---|---|
| proxy_buffering | Enables or disables response buffering from proxied servers | on |
| proxy_buffers | Sets number and size of buffers for response | 8 4k or 8 16k (depending on platform) |
| proxy_buffer_size | Sets size of buffer for the first part of the response | 4k or 8k |
Key Takeaways
Enable
proxy_buffering to improve performance by buffering backend responses before sending to clients.Place
proxy_buffering inside http, server, or location blocks in your Nginx config.Configure
proxy_buffers and proxy_buffer_size to optimize memory use and response speed.Avoid disabling buffering unless you have a specific reason, as it can increase backend load and slow responses.
Test your configuration after changes to ensure buffering behaves as expected.