worker_processes auto; # 自动设置为CPU核心数
worker_cpu_affinity auto; # CPU亲和性绑定
worker_rlimit_nofile 65535; # 每个worker进程最大打开文件数
events {
use epoll; # Linux下高性能事件模型
worker_connections 10240; # 每个worker最大连接数
multi_accept on; # 一次接受多个新连接
accept_mutex off; # 高负载时关闭互斥锁
}
http {
sendfile on; # 启用零拷贝传输
tcp_nopush on; # 优化TCP数据包发送
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 长连接超时
keepalive_requests 100; # 单个长连接最大请求数
client_header_timeout 15s; # 客户端请求头超时
client_body_timeout 15s; # 客户端请求体超时
send_timeout 10s; # 响应发送超时
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
access_log off;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
proxy_cache_lock on;
}
}
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fcgi_cache:10m inactive=60m;
location ~ \.php$ {
fastcgi_cache fcgi_cache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_methods GET HEAD;
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
}
upstream backend {
least_conn; # 最少连接算法
server 10.0.0.1:80 weight=5;
server 10.0.0.2:80 weight=3;
server 10.0.0.3:80 backup;
keepalive 32; # 保持的连接数
}
upstream backend {
server 10.0.0.1:80 max_fails=3 fail_timeout=30s;
server 10.0.0.2:80 max_fails=3 fail_timeout=30s;
check interval=5000 rise=2 fall=3 timeout=1000 type=http;
check_http_send "HEAD / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
server_tokens off; # 隐藏Nginx版本信息
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=req_limit burst=20 nodelay;
}
}
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
netstat -anp | grep nginx | wc -l
top -p $(pgrep -d',' nginx)
# 编译时添加模块
./configure --add-dynamic-module=/path/to/module
# nginx.conf中加载
load_module modules/ngx_http_geoip_module.so;
access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;
# 测试配置
nginx -t
# 热重载
nginx -s reload
location /large_files/ {
aio on;
directio 4m;
output_buffers 1 1m;
}
通过以上架构设计和优化策略,可以显著提升Nginx服务器的性能和稳定性,满足高并发场景下的业务需求。实际应用中应根据具体业务特点和服务器资源情况进行针对性调整。