Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Linux & Mac & Bash Command Dictionary

  1. Home
  2. Linux & Mac & Bash Command Dictionary
  3. Nginx Performance Tuning

Nginx Performance Tuning

Nginx performance tuning focuses on four key areas: setting worker_processes to match your CPU core count, using keepalive_timeout to reuse connections, enabling sendfile to speed up static file delivery, and compressing responses with gzip. Combining these directives reduces wasted server resources and improves response times for end users.

Syntax

# -----------------------------------------------
#  worker_processes / worker_connections
# -----------------------------------------------

# worker_processes {number | auto}
#   → Sets the number of Nginx worker processes.
#   → Use auto to match the number of CPU cores automatically.
#   Example: worker_processes auto;

# worker_connections {number}
#   → Sets the maximum number of simultaneous connections per worker process.
#   → Total concurrent connections = worker_processes × worker_connections.
#   Example: worker_connections 1024;

# -----------------------------------------------
#  keepalive_timeout
# -----------------------------------------------

# keepalive_timeout {seconds} [{header seconds}]
#   → Sets how long (in seconds) to keep an HTTP Keep-Alive connection open.
#   → Higher values reduce connection overhead, but hold file descriptors
#     (FDs) open longer.
#   → Values between 10 and 30 seconds are common in production.
#   Example: keepalive_timeout 15;

# -----------------------------------------------
#  sendfile / tcp_nopush / tcp_nodelay
# -----------------------------------------------

# sendfile {on | off}
#   → Uses the kernel's sendfile(2) system call to send files.
#   → Transfers data directly from disk to network, bypassing user space,
#     which speeds up static file delivery.
#   Example: sendfile on;

# tcp_nopush {on | off}
#   → Effective when sendfile is on. Combines the response header and the
#     beginning of the file into a single TCP packet.
#   → Use together with sendfile on.
#   Example: tcp_nopush on;

# tcp_nodelay {on | off}
#   → Disables the Nagle algorithm, sending small packets immediately.
#   → Effective for keepalive connections.
#   Example: tcp_nodelay on;

# -----------------------------------------------
#  gzip compression
# -----------------------------------------------

# gzip {on | off}
#   → Enables gzip compression for responses.
#   Example: gzip on;

# gzip_types {MIME type ...}
#   → Specifies which MIME types to compress.
#   → text/html is always compressed and does not need to be listed here.
#   Example: gzip_types text/plain text/css application/json application/javascript text/xml;

# gzip_comp_level {1-9}
#   → Sets the gzip compression level.
#   → 1 is fastest (least compression), 9 is highest compression (slowest).
#   → A value of 4-6 is recommended for a good balance of CPU cost and ratio.
#   Example: gzip_comp_level 5;

# gzip_min_length {bytes}
#   → Responses smaller than this size will not be compressed.
#   → Compressing very small files yields little benefit; 256-1024 bytes is common.
#   Example: gzip_min_length 256;

# gzip_vary {on | off}
#   → Adds a Vary: Accept-Encoding header to responses.
#   → Needed so CDNs and proxies can correctly cache both compressed and
#     uncompressed versions.
#   Example: gzip_vary on;

# -----------------------------------------------
#  Buffers / client size limits
# -----------------------------------------------

# client_max_body_size {size}
#   → Sets the maximum allowed size of the client request body.
#   → Increase this when your application accepts file uploads.
#   Example: client_max_body_size 10m;

# client_body_buffer_size {size}
#   → Sets the in-memory buffer size for reading the request body.
#   → Data exceeding this size is written to a temporary file on disk.
#   Example: client_body_buffer_size 16k;

# -----------------------------------------------
#  File cache
# -----------------------------------------------

# open_file_cache max={number} inactive={seconds}
#   → Caches file descriptors, file sizes, and modification times.
#   → Reduces disk I/O on servers that serve many static files.
#   Example: open_file_cache max=1000 inactive=30s;

# open_file_cache_valid {seconds}
#   → Sets how often cached entries are revalidated.
#   Example: open_file_cache_valid 60s;

Directive Reference

DirectiveDescription
worker_processes autoAutomatically sets the number of worker processes to match the CPU core count, making full use of available cores.
worker_connections 1024Sets the maximum number of simultaneous connections per worker. The total connection limit is worker_processes multiplied by worker_connections.
keepalive_timeout 15Sets how many seconds to keep a Keep-Alive connection open. Reduces reconnection overhead, but holding it too long wastes resources.
sendfile onUses the kernel's sendfile() system call to send static files directly to the network, without copying through user space.
tcp_nopush onCombines the response header and the start of the file into one packet when used with sendfile.
tcp_nodelay onDisables the Nagle algorithm so small packets are sent immediately over keepalive connections.
gzip onEnables gzip compression, significantly reducing the size of text-based responses.
gzip_types ...Specifies which MIME types to compress. text/html is compressed automatically.
gzip_comp_level 5Sets the gzip compression level (1–9). A value of 4–6 offers a good balance between CPU cost and compression ratio.
gzip_min_length 256Skips compression for responses smaller than the specified byte count, avoiding unnecessary processing for tiny files.
gzip_vary onAdds a Vary: Accept-Encoding header so CDNs and proxies can distinguish between compressed and uncompressed versions.
client_max_body_size 10mSets the maximum allowed size of a client request body. Adjust this to match your file upload requirements.
client_body_buffer_size 16kSets the in-memory buffer size for the request body. Any data beyond this limit is written to a temporary file on disk.
open_file_cache max=1000 inactive=30sCaches file descriptors, sizes, and modification times. Reduces disk I/O on servers that serve many static files.
open_file_cache_valid 60sSpecifies how often cached entries are revalidated.

Example

/etc/nginx/nginx.conf
# -----------------------------------------------
#  Nginx performance tuning for production
#  Kiryu Group EC site (kiryu-group.example.com)
# -----------------------------------------------

# Automatically set the number of worker processes to match CPU cores.
worker_processes auto;

# Set the maximum number of file descriptors Nginx can open.
# Should be greater than the total of all worker_connections.
worker_rlimit_nofile 65535;

events {
    # Maximum simultaneous connections per worker.
    # Total connection limit = worker_processes × worker_connections.
    worker_connections 1024;

    # Linux only. Accepts multiple connections at once.
    multi_accept on;
}

http {
    # -----------------------------------------------
    #  Basic settings
    # -----------------------------------------------

    # Load the MIME type definitions file.
    include /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # -----------------------------------------------
    #  Static file transfer optimization
    # -----------------------------------------------

    # Use the kernel's sendfile() to send files directly to the network.
    sendfile        on;

    # Combine the response header and the start of the file into one packet.
    # (Only effective when sendfile is on.)
    tcp_nopush      on;

    # Send small data immediately over Keep-Alive connections.
    tcp_nodelay     on;

    # -----------------------------------------------
    #  Keep-Alive settings
    # -----------------------------------------------

    # Keep client connections alive for 15 seconds.
    # Too short increases reconnection cost; too long holds FDs open.
    keepalive_timeout 15;

    # -----------------------------------------------
    #  File cache (useful when serving many static files)
    # -----------------------------------------------

    # Cache file descriptors, sizes, and modification times in memory.
    # Entries not accessed within 30 seconds are released.
    open_file_cache          max=1000 inactive=30s;

    # Revalidate cached entries every 60 seconds.
    open_file_cache_valid    60s;

    # -----------------------------------------------
    #  gzip compression
    # -----------------------------------------------

    # Enable gzip compression.
    gzip              on;

    # text/html is always compressed (no need to list it here).
    # Add other common text-based MIME types below.
    gzip_types
        text/plain
        text/css
        text/javascript
        application/json
        application/javascript
        application/x-javascript
        text/xml
        application/xml
        application/xml+rss
        image/svg+xml;

    # Level 5 offers a good balance between CPU cost and compression ratio.
    gzip_comp_level   5;

    # Do not compress responses smaller than 256 bytes.
    gzip_min_length   256;

    # Allow CDNs and reverse proxies to correctly cache compressed responses.
    gzip_vary         on;

    # -----------------------------------------------
    #  Client size limits
    # -----------------------------------------------

    # Allow up to 20 MB for image and video uploads.
    client_max_body_size     20m;

    # In-memory buffer for request bodies (overflow is written to disk).
    client_body_buffer_size  16k;

    # -----------------------------------------------
    #  Virtual host configuration
    # -----------------------------------------------

    # Kiryu Group EC site
    server {
        listen       80;
        server_name  kiryu-group.example.com;

        root /var/www/html/kiryu-shop;
        index  index.php index.html;

        # Set long-term cache headers for static assets.
        location ~* \.(css|js|jpg|jpeg|png|gif|ico|woff2)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php$ {
            fastcgi_pass   unix:/run/php/php8.2-fpm.sock;
            fastcgi_index  index.php;
            include        fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    }
}

Run the following command:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl reload nginx
$ curl -I -H "Accept-Encoding: gzip" https://kiryu-group.example.com/
HTTP/2 200
server: nginx/1.26.0
content-type: text/html; charset=UTF-8
content-encoding: gzip
vary: Accept-Encoding

Overview

Nginx performance tuning is divided into four main areas: process configuration, static file transfer, connection management, and compression. Use worker_processes auto to fully utilize all CPU cores, and combine sendfile on with tcp_nopush on for kernel-level high-speed file transfers. Setting keepalive_timeout to an appropriate value (around 10–30 seconds) reduces connection re-establishment overhead while avoiding unnecessary resource usage. gzip compression significantly reduces the size of text-based responses such as HTML, CSS, and JavaScript, cutting network transfer volume. Note that images (JPEG, PNG) are already compressed and should not be included in gzip_types. For basic Nginx server block configuration, see Nginx Configuration. For HTTPS and TLS security settings, see Nginx SSL Configuration.

If you find any errors or copyright issues, please .