0
0
NginxHow-ToBeginner · 4 min read

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_buffers and proxy_buffer_size properly, leading to inefficient memory use or slow responses.
  • Placing proxy_buffering outside of http, server, or location blocks, 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

DirectiveDescriptionDefault Value
proxy_bufferingEnables or disables response buffering from proxied serverson
proxy_buffersSets number and size of buffers for response8 4k or 8 16k (depending on platform)
proxy_buffer_sizeSets size of buffer for the first part of the response4k 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.