快速结论
通过Gzip压缩+缓存策略+连接优化三板斧,可让网站加载速度提升50%-200%。2核2GB的云服务器经过Nginx优化后,轻松支撑日均万级PV。推荐搭配阿里云ECS或腾讯云轻量使用。
为什么要优化Nginx
默认安装的Nginx配置偏保守,适合通用场景但无法发挥服务器最佳性能:
| 问题 | 默认配置 | 优化后 |
|---|---|---|
| 并发处理 | worker_processes 1 | 自动匹配CPU核心 |
| 压缩传输 | 未开启Gzip | 减少60-80%传输体积 |
| 静态缓存 | 无缓存策略 | 浏览器缓存30天 |
| 连接复用 | 保守设置 | keepalive长连接 |
| 文件读取 | 标准模式 | sendfile零拷贝 |
基础配置优化
1. Worker进程配置
# /etc/nginx/nginx.conf 主配置
# 自动匹配CPU核心数
worker_processes auto;
# 每个worker的最大连接数
events {
worker_connections 2048;
multi_accept on;
use epoll;
}配置说明:
worker_processes auto:自动设为CPU核心数,2核服务器=2个workerworker_connections 2048:每个worker处理2048个并发连接multi_accept on:一次接受多个新连接use epoll:Linux高效事件模型
2. HTTP全局优化
http {
# 文件传输优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 连接超时设置
keepalive_timeout 65;
keepalive_requests 100;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 请求体大小限制
client_max_body_size 50m;
# 隐藏Nginx版本号(安全)
server_tokens off;
}3. Gzip压缩(最关键)
http {
# 开启Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_buffers 16 8k;
# 压缩的MIME类型
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/rss+xml
application/atom+xml
image/svg+xml
font/ttf
font/woff
font/woff2;
}压缩效果实测:
| 文件类型 | 原始大小 | 压缩后 | 压缩率 |
|---|---|---|---|
| HTML | 50KB | 12KB | 76% |
| CSS | 120KB | 22KB | 82% |
| JavaScript | 300KB | 65KB | 78% |
| JSON API | 80KB | 15KB | 81% |
静态资源缓存
浏览器缓存策略
server {
# 图片缓存30天
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# CSS/JS缓存7天
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
access_log off;
}
# 字体文件缓存1年
location ~* \.(woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
}关闭静态资源日志
静态资源的访问日志无意义,关闭后可减少磁盘IO:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
access_log off;
log_not_found off;
}高级优化
1. HTTP/2 启用
HTTP/2多路复用可大幅提升加载速度:
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# SSL优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}2. 反向代理优化(Node.js/Python后端)
upstream backend {
server 127.0.0.1:3000;
keepalive 32;
}
server {
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
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;
# 缓冲优化
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}3. 限速防护
# 定义限速区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn:10m;
server {
# API限速:每秒10个请求,突发20个
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_conn conn 10;
}
}4. 安全Header
server {
# 安全响应头
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;
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}性能测试验证
优化完成后,用以下工具验证效果:
ab压测
# 模拟100并发、1000次请求
ab -n 1000 -c 100 https://你的域名/curl查看响应头
# 检查Gzip和缓存是否生效
curl -I -H "Accept-Encoding: gzip" https://你的域名/应看到:
Content-Encoding: gzip
Cache-Control: public, max-age=2592000Google PageSpeed Insights
访问 PageSpeed Insights 输入网址,目标分数:
- 移动端 ≥ 70分
- 桌面端 ≥ 90分
不同场景的完整配置
静态网站/博客
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html;
# SPA单页应用路由
location / {
try_files $uri $uri/ /index.html;
}
# 全局Gzip + 缓存
gzip on;
gzip_types text/plain text/css application/json application/javascript;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 30d;
access_log off;
}
}WordPress网站
server {
listen 80;
server_name example.com;
root /var/www/wordpress;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache_bypass $http_pragma;
}
# 禁止直接访问wp-config
location = /wp-config.php {
deny all;
}
}推荐云服务器 + Nginx方案
| 场景 | 推荐配置 | 预期性能 | 方案 |
|---|---|---|---|
| 个人博客 | 2核2G | 日1万PV | 阿里云轻量38元/年 |
| 企业官网 | 2核4G | 日5万PV | 腾讯云轻量88元/年 |
| 电商平台 | 4核8G | 日20万PV | 华为云ECS |
总结
Nginx优化的核心三板斧:Gzip压缩(减体积)+ 缓存策略(减请求)+ 连接优化(提效率)。完成上述配置后,同样的服务器硬件可承载2-3倍的访问量,页面加载速度提升50%以上。
修改Nginx配置后,先用
nginx -t检查语法,确认无误再systemctl reload nginx重载。