前言
Nginx 是当前互联网上使用最广泛的 Web 服务器之一,它占据了全球超过 30% 的网站份额。对于个人站长来说,Nginx 不仅是将网站内容呈现给用户的桥梁,更是网站性能和安全的第一道防线。然而,很多个人站长的 Nginx 配置停留在"让它跑起来就行"的水平,远未发挥其真正的潜力。本文将从性能调优和安全加固两个维度,分享一套完整的 Nginx 进阶配置指南。
一、Nginx 基础架构理解
1.1 进程模型
Nginx 采用 Master-Worker 多进程模型,与传统的 Apache prefork 模型有本质区别:
- Master 进程:负责读取配置文件、管理工作进程、执行平滑重载
- Worker 进程:实际处理客户端请求,每个 Worker 是单线程但基于事件驱动(epoll/kqueue)实现高并发
这种架构的优势在于:一个 Worker 进程可以同时处理数千个连接,而不会因为线程切换带来性能开销。
1.2 事件驱动模型
Nginx 使用异步非阻塞 I/O 模型。当 Worker 进程处理一个请求时,不会阻塞等待 I/O 操作完成,而是注册一个回调后继续处理其他请求。这就像餐厅里一个服务员同时多桌服务——下单后不站在厨房门口等菜,而是去服务其他客人。
# 事件模块的核心配置
events {
use epoll; # Linux 上使用 epoll(最高效的事件模型)
worker_connections 10240; # 每个 Worker 的最大连接数
multi_accept on; # 一次接受多个新连接
accept_mutex_delay 100ms; # 互斥锁延迟
}二、性能调优实战
2.1 Worker 进程配置
Worker 数量不是越多越好,通常设置为 CPU 核心数即可:
# 自动检测 CPU 核心数
worker_processes auto;
# 绑定 Worker 到指定 CPU 核心,避免进程迁移带来的缓存失效
worker_cpu_affinity auto;
# 提高 Worker 进程的优先级
worker_priority -5;
# 每个 Worker 可以打开的最大文件数
worker_rlimit_nofile 65535;2.2 连接优化
http {
# 保持连接超时设置
keepalive_timeout 65;
keepalive_requests 1000; # 单个 keep-alive 连接最多处理 1000 个请求
# 客户端请求体大小限制(根据网站需求调整)
client_max_body_size 50m;
# 缓冲区优化
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# 输出缓冲区
output_buffers 32 32k;
postpone_output 1460;
# 读取超时设置
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;
}2.3 静态文件缓存
对于个人网站,大部分流量是静态资源(CSS、JS、图片)。通过合理配置缓存,可以极大减轻服务器压力:
# 静态资源缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|webp|woff2?|ttf|eot|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off; # 静态资源不记录访问日志,节省 I/O
log_not_found off; # 不记录 404 错误日志
}
location ~* \.(html|htm)$ {
expires 1h;
add_header Cache-Control "public, must-revalidate";
}2.4 Gzip 压缩
启用 Gzip 或 Brotli 压缩可以大幅减少传输数据量(通常可减少 60-80%):
# Gzip 压缩配置
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6; # 压缩级别 1-9,推荐 6(平衡 CPU 和压缩率)
gzip_min_length 256; # 小于 256 字节的文件不压缩
gzip_types
text/plain
text/css
text/javascript
application/javascript
application/json
application/xml+rss
application/octet-stream
image/svg+xml
image/x-icon
font/woff
font/woff2;
# Brotli 压缩(需要编译 brotli 模块)
# brotli on;
# brotli_comp_level 6;
# brotli_types text/plain text/css text/javascript application/javascript...2.5 反向代理缓存
如果网站使用了反向代理(例如将请求转发到 PHP-FPM 或后端应用服务器),启用代理缓存可以大幅提升性能:
# 定义缓存路径和参数
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
location / {
proxy_cache mycache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 60m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502;
proxy_cache_background_update on;
proxy_cache_lock on;
# 向后端添加缓存标识头部
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}X-Cache-Status 头部可以帮助调试:值为 HIT 表示缓存命中,MISS 表示未命中。
2.6 SSL/TLS 性能优化
HTTPS 不再是可选项,而是标配。优化 SSL 配置可以减少握手延迟:
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL 证书路径
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
# 优先使用现代加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 1.1.1.1 valid=300s;
resolver_timeout 5s;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
}三、安全加固配置
3.1 安全头部
添加 HTTP 安全头部可以防范多种常见的 Web 攻击:
# 安全头部配置
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self' https:; connect-src 'self';" always;3.2 限制请求速率
防止暴力破解和 CC 攻击:
# 定义限流区域
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
# 对登录页面限流
location /wp-login.php {
limit_req zone=login burst=10 nodelay;
limit_conn addr 5;
# ... 其他配置
}
# 对 API 限流
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_conn addr 10;
}
}3.3 隐藏 Nginx 版本号
防止攻击者利用已知漏洞:
# 在 http 块中配置
http {
server_tokens off; # 隐藏 Nginx 版本号
# 也可以自定义错误页面
error_page 404 /404.html;
error_page 502 /502.html;
}3.4 限制访问路径
保护敏感文件和目录:
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问敏感文件类型
location ~* \.(bak|config|sql|log|ini|sh|swp|old)$ {
deny all;
}
# 保护管理员路径
location /admin/ {
allow 192.168.1.0/24; # 仅允许内网访问
allow 你的IP; # 允许你的 IP
deny all;
# 密码保护
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}3.5 防爬虫和 CC 攻击
通过限制特定 User-Agent 和请求行为来防止恶意爬虫:
# 阻止恶意爬虫
if ($http_user_agent ~* (curl|wget|python-requests|scrapy|HttpClient)) {
return 403;
}
# 或者更优雅的方式(Map 方法)
map $http_user_agent $bad_bot {
default 0;
~*curl 1;
~*wget 1;
~*python-requests 1;
~*scrapy 1;
~*HttpClient 1;
~*Go-http-client 1;
}
server {
if ($bad_bot) {
return 403;
}
}3.6 ModSecurity 基础配置(可选)
对于安全要求较高的网站,可以考虑集成 ModSecurity WAF:
# 需要编译 ModSecurity 模块
# ./configure --with-compat --add-dynamic-module=/path/to/ModSecurity-nginx
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsecurity.conf;
}四、日志优化
4.1 日志格式
自定义日志格式,记录更多有用的信息:
# 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';
log_format json escape=json '{"time":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"bytes":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"ua":"$http_user_agent"}';4.2 日志轮转
防止日志文件无限增长导致磁盘占满:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}五、监控与调优工具
5.1 状态监控
开启 Nginx 的 Status 模块,实时查看运行状态:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}访问 /nginx_status 可以看到:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 1065.2 压力测试
使用 ab(Apache Bench)或 wrk 进行压力测试:
# 安装 wrk
sudo apt install wrk
# 压力测试(100 个并发连接,持续 30 秒)
wrk -t12 -c100 -d30s https://yourdomain.com5.3 配置语法检查
每次修改配置后,务必检查语法:
# 检查配置语法
nginx -t
# 平滑重载配置(不影响正在处理的连接)
nginx -s reload六、完整配置模板
最后,分享一份经过生产环境验证的 Nginx 配置模板,可以作为个人网站的起点:
user www-data;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;
events {
use epoll;
worker_connections 10240;
multi_accept on;
}
http {
## 基础设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
types_hash_max_size 2048;
server_tokens off;
## MIME 类型
include /etc/nginx/mime.types;
default_type application/octet-stream;
## 日志设置
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
## Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml;
## 安全头部
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
## 缓存配置
open_file_cache max=10000 inactive=60s;
open_file_cache_valid 80s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
## SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
## 虚拟主机
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}结语
Nginx 的性能调优和安全加固是一个持续的过程,没有"一劳永逸"的万能配置。本文提供的配置参数和策略可以作为良好的起点,但实际部署中需要根据你的服务器硬件、网站流量和业务特点进行针对性调整。
建议每次修改配置后,使用 nginx -t 检查语法,用 nginx -s reload 平滑重载。同时,通过 nginx_status 模块持续监控服务器状态,根据实际运行数据逐步优化参数。
良好的 Nginx 配置可以让你用有限的服务器资源支撑更高的访问量,同时有效防范常见的安全威胁。花时间打磨你的 Nginx 配置,是个人网站运维中最值得投入的精力之一。