worker_processes auto;
)events {
use epoll; # Linux高效事件模型
worker_connections 2048;
multi_accept on; # 一次接受所有新连接
accept_mutex off; # 高负载时关闭互斥锁
}
http {
sendfile on; # 启用零拷贝传输
tcp_nopush on; # 合并数据包减少报文数量
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65;
keepalive_requests 1000; # 单个连接最大请求数
reset_timedout_connection on; # 关闭超时连接释放资源
}
client_body_buffer_size 16k;
client_header_buffer_size 4k;
client_max_body_size 8m;
large_client_header_buffers 4 16k;
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
access_log off;
add_header Cache-Control "public, no-transform";
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
gzip on;
gzip_min_length 1k;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_vary on;
upstream backend {
least_conn; # 最少连接负载均衡
server 192.168.1.1:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.2:8080 max_fails=3 fail_timeout=30s;
keepalive 32; # 连接池大小
}
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_keep_conn on;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 256k;
fastcgi_read_timeout 300;
}
# 增加最大文件描述符数
echo "ulimit -n 65535" >> /etc/profile
# 调整TCP参数
echo "net.ipv4.tcp_max_syn_backlog = 8192" >> /etc/sysctl.conf
echo "net.core.somaxconn = 8192" >> /etc/sysctl.conf
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
sysctl -p
noatime,nodiratime
挂载选项location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;
aio threads; # 启用异步I/O线程池
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
通过以上综合优化策略,Nginx服务器可以轻松应对数万甚至数十万的并发连接,同时保持高效稳定的服务能力。