To optimize Nginx performance under high traffic, you need to start from six aspects: configuration, system, cache, compression, log and expansion: 1. Set worker_processes to the number of CPU cores and increase worker_connections (such as 4096) to improve concurrency capabilities; 2. Adjust system file descriptor restrictions and TCP parameters (such as somaxconn, tcp_tw_reuse), and enable epoll event model; 3. Enable long-term cache and open_file_cache for static resources to reduce disk I/O; 4. Enable moderate gzip compression (levels 1–3) to save bandwidth; 5. Turn off static resource access logs and use buffered logs to reduce write frequency; 6. Enable horizontal scaling through upstream load balancing and CDN. Ultimately, the effect must be verified through stress testing tools and continuously monitored key indicators to ensure complete and effective optimization.
When running Nginx under high traffic—say, thousands or tens of thousands of concurrent connections—default settings won't cut it. You'll need to tune both Nginx itself and the underlying system to handle the load efficiently without dropping requests or spiking latency.

Here's how to optimize Nginx for high traffic, broken down into key areas:
1. Tune Nginx Worker Processes & Connections
Nginx uses an event-driven, asynchronous architecture. To maximize CPU utilization:

- Set
worker_processes
to match the number of CPU cores:worker_processes auto;
- Increase
worker_connections
per worker:events { worker_connections 4096; }
With 4 workers × 4096 connections = 16,384 concurrent connections per Nginx instance (theoretical max). Monitor with
netstat
orss -s
.
? Tip: Use
worker_rlimit_nofile
to raise the file descriptor limit per worker if hitting "too many open files" errors.
2. Optimize Kernel & System Limits
Nginx is only as fast as the OS allows. Tune these:
Increase file descriptor limits (
/etc/security/limits.conf
):nginx soft nofile 65536 nginx hard nofile 65536
Tune TCP stack for high concurrency (
/etc/sysctl.conf
):net.core.somaxconn = 65535 net.ipv4.tcp_max_syn_backlog = 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.ip_local_port_range = 1024 65535
Apply with
sysctl -p
.Enable
epoll
(Linux) :events { use epoll; multi_accept on; }
3. Optimize Static Content & Caching
- Serve static assets directly from memory or fast storage:
location /static/ { expires 1y; add_header Cache-Control "public, immutable"; }
- Use
open_file_cache
to reduce disk I/O:open_file_cache max=100000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;
4. Use Gzip (But Wisely)
Compressing responses saves bandwidth but costs CPU. Balance it:
gzip on; gzip_min_length 1024; gzip_comp_level 3; # Level 1–3 for high traffic (CPU vs size tradeoff) gzip_types text/plain text/css application/json application/javascript;
5. Monitor & Log Efficiently
- Disable access logs for static assets:
location /static/ { access_log off; }
- Use buffered logging:
access_log /var/log/nginx/access.log main buffer=32k flush=1m;
6. Scale Horizontally (If Needed)
- Load balance across multiple Nginx instances (or apps) using
upstream
:upstream backend { least_conn; server app1:8080; server app2:8080; }
- Consider using a CDN for static content to offload Nginx entirely.
Final Tip : Always test changes under realistic load using tools like ab
, wrk
, or hey
. Monitor metrics like:
-
nginx_status
(enable withstub_status
) - CPU, memory, and network I/O
- 5xx errors and request latency
Optimizing Nginx isn't just about config—it's about aligning the whole stack: OS, network, app, and infrastructure. Start with the basics above, then iterate based on real-world performance.
The above is the detailed content of Optimizing Nginx for High Traffic. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The main Nginx configuration file is usually located in the conf directory under /etc/nginx/nginx.conf (Ubuntu/Debian, CentOS/RHEL), /usr/local/etc/nginx/nginx.conf (macOSHomebrew) or the source code installation path; you can view the loaded configuration path through nginx-t, ps-ef|grepnginx check the path specified by the startup parameters, or use find/-namenginx.conf and locatenginx.conf to quickly find; the configuration file structure includes global settings, events blocks and http blocks, and common site configurations are common.

When Nginx experiences a "Toomyopenfiles" error, it is usually because the system or process has reached the file descriptor limit. Solutions include: 1. Increase the soft and hard limits of Linux system, set the relevant parameters of nginx or run users in /etc/security/limits.conf; 2. Adjust the worker_connections value of Nginx to adapt to expected traffic and ensure the overloaded configuration; 3. Increase the upper limit of system-level file descriptors fs.file-max, edit /etc/sysctl.conf and apply changes; 4. Optimize log and resource usage, and reduce unnecessary file handle usage, such as using open_l

The browser prompts the "mixed content" warning because HTTP resources are referenced in the HTTPS page. The solution is: 1. Check the source of mixed content in the web page, view console information through the developer tool or use online tool detection; 2. Replace the resource link to HTTPS or relative paths, change http:// to https:// or use the //example.com/path/to/resource.js format; 3. Update the content in the CMS or database, replace the HTTP link in the article and page one by one, or replace it in batches with SQL statements; 4. Set the server to automatically rewrite the resource request, and add rules to the server configuration to force HTTPS to jump.

Enabling Gzip compression can effectively reduce the size of web page files and improve loading speed. 1. The Apache server needs to add configuration in the .htaccess file and ensure that the mod_deflate module is enabled; 2.Nginx needs to edit the site configuration file, set gzipon and define the compression type, minimum length and compression level; 3. After the configuration is completed, you can verify whether it takes effect through online tools or browser developer tools. Pay attention to the server module status and MIME type integrity during operation to ensure normal compression operation.

The stub_status module displays the real-time basic status information of Nginx. Specifically, it includes: 1. The number of currently active connections; 2. The total number of accepted connections, the total number of processing connections, and the total number of requests; 3. The number of connections being read, written, and waiting. To check whether it is enabled, you can check whether the --with-http_stub_status_module parameter exists through the command nginx-V. If not enabled, recompile and add the module. When enabled, you need to add location blocks to the configuration file and set access control. Finally, reload the Nginx service to access the status page through the specified path. It is recommended to use it in combination with monitoring tools, but it is only available for internal network access and cannot replace a comprehensive monitoring solution.

To enable Nginx's HTTP/2 or HTTP/3 support, the prerequisites must be met and configured correctly; HTTP/2 requires Nginx1.9.5, OpenSSL1.0.2 and HTTPS environment; add --with-http_v2_module module during configuration, modify the listening statement to listen443sslhttp2; and overload the service; HTTP/3 is based on QUIC, and third-party modules such as nginx-quic are required to introduce BoringSSL or OpenSSLQUIC branches during compilation, and configure UDP listening ports; common problems during deployment include ALPN not enabled, certificate incompatible, firewall restrictions and compilation errors, it is recommended to use priority

The "Addressalreadyinuse" error means that another program or service in the system has occupied the target port or IP address. Common reasons include: 1. The server is running repeatedly; 2. Other services occupy ports (such as Apache occupying port 80, causing Nginx to fail to start); 3. The port is not released after crash or restart. You can troubleshoot through the command line tool: use sudolsof-i:80 or sudolnetstat-tulpn|grep:80 in Linux/macOS; use netstat-ano|findstr:80 in Windows and check PID. Solutions include: 1. Stop the conflicting process (such as sudos

A/B testing can be implemented through Nginx's split_clients module, which distributes traffic proportionally to different groups based on user attribute hashing. The specific steps are as follows: 1. Use the split_clients instruction to define the grouping and proportions in the http block, such as 50%A and 50%B; 2. Use variables such as $cookie_jsessionid, $remote_addr or $arg_uid as hash keys to ensure that the same user is continuously allocated to the same group; 3. Use the corresponding backend through if conditions in the server or location block; 4. Record the grouping information through a custom log format to analyze the effect; 5. Track the performance of each group with the monitoring tool
