目录
为什么需要高级Nginx配置
Nginx(读作"Engine-X")是2026年全球最受欢迎的Web服务器,用于超过34%的网站。其事件驱动的非阻塞I/O架构使其能够以极低的内存占用处理数万个并发连接。
虽然默认安装就能运行,但生产VPS需要针对性能、安全性和可靠性进行专门调优。
| 配置项 | 默认值 | 优化后 |
|---|---|---|
| 工作进程数 | 1 | = CPU核心数(auto) |
| 工作连接数 | 768 | 1024–65535 |
| Gzip压缩 | 关闭 | 开启,级别5 |
| SSL协议 | TLSv1 TLSv1.1 TLSv1.2 | 仅TLSv1.2 TLSv1.3 |
| 安全标头 | 无 | HSTS, X-Frame-Options等 |
| 速率限制 | 无 | 每IP限制请求/秒 |
| FastCGI缓存 | 关闭 | WordPress专用缓存 |
安装与文件结构
在Ubuntu 22.04/24.04 LTS上安装Nginx:
sudo apt update && sudo apt install nginx -y sudo systemctl enable nginx sudo systemctl start nginx
关键文件位置
/etc/nginx/nginx.conf— 主配置文件(全局设置)/etc/nginx/sites-available/— 每个域名的服务器块文件/etc/nginx/sites-enabled/— 活动服务器块的符号链接/var/log/nginx/access.log— 访问日志/var/log/nginx/error.log— 错误日志
优化后的nginx.conf
user www-data;
worker_processes auto; # 自动使用所有CPU核心
pid /run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
server_tokens off; # 隐藏Nginx版本号
include /etc/nginx/mime.types;
default_type application/octet-stream;
gzip on; # 详见Gzip章节
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
提示:server_tokens off隐藏HTTP响应头中的Nginx版本号,防止攻击者识别版本并利用对应漏洞。
虚拟主机(服务器块)
Nginx将虚拟主机称为服务器块(Server Block)。通过SNI(服务器名称指示),单个IP地址可以托管多个域名。
创建服务器块
sudo nano /etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/public;
index index.php index.html index.htm;
# PHP-FPM处理器
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
# 启用服务器块 sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t # 测试配置 sudo nginx -s reload # 重新加载
SSL/TLS配置
2026年,SSL对所有生产网站都是必不可少的。使用Let's Encrypt获取免费SSL证书:
安装Certbot
sudo apt install certbot python3-certbot-nginx -y sudo certbot --nginx -d example.com -d www.example.com
加固的SSL配置
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 仅允许TLS 1.2和1.3
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
# OCSP装订
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 8.8.8.8 valid=300s;
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
}
# HTTP重定向至HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
⚠️ 重要:生产服务器上绝对不要启用TLSv1或TLSv1.1——两者都有已知漏洞。只使用TLSv1.2和TLSv1.3。
Gzip压缩
Gzip可将文本文件大小减少60-80%。在nginx.conf的http {}块中添加:
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5; # 级别1-9(5=CPU与压缩比的平衡)
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256; # 不压缩小于256字节的文件
gzip_types
application/javascript
application/json
application/xml
font/ttf
image/svg+xml
text/css
text/javascript
text/plain
text/xml;
注意:不要对已压缩格式(JPEG、PNG、WebP、ZIP、MP4)使用Gzip——它们不会进一步压缩,只会浪费CPU资源。
安全标头
安全标头可防范常见的Web攻击。在服务器块中添加:
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header X-XSS-Protection "1; mode=block" always; add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always; # HSTS——在SSL正常运行至少一周后启用 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
| 标头 | 防护对象 |
|---|---|
| X-Frame-Options: SAMEORIGIN | 点击劫持攻击 |
| X-Content-Type-Options: nosniff | MIME类型混淆攻击 |
| Referrer-Policy | 通过引用头泄露信息 |
| X-XSS-Protection | 反射型XSS(旧版浏览器) |
| Strict-Transport-Security | SSL剥离、中间人攻击 |
| Permissions-Policy | 未经授权的浏览器API访问 |
速率限制
速率限制限制单个IP可以发送的请求数量,防止DDoS攻击和暴力破解登录:
# 添加到nginx.conf的http {}块
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
# WordPress登录保护
location = /wp-login.php {
limit_req zone=login burst=3 nodelay;
limit_conn addr 3;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}
# API端点
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
缓存与反向代理
FastCGI缓存将PHP输出存储在磁盘上,使后续请求速度提升10-50倍:
# 添加到http {}块
fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
# 在server {}块中
set $skip_cache 0;
# 跳过缓存:POST请求、已登录用户
if ($request_method = POST) { set $skip_cache 1; }
if ($http_cookie ~* "wordpress_logged_in") { set $skip_cache 1; }
location ~ \.php$ {
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-FastCGI-Cache $upstream_cache_status;
}
Node.js/Python反向代理
server {
listen 443 ssl http2;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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;
}
}
WordPress优化
WordPress在Nginx上需要特殊配置,因为Nginx不支持.htaccess,使用try_files指令处理固定链接:
server {
listen 443 ssl http2;
server_name myblog.com www.myblog.com;
root /var/www/myblog.com/public;
index index.php;
# WordPress固定链接处理
location / {
try_files $uri $uri/ /index.php?$args;
}
# 阻止敏感文件直接访问
location ~* /(?:uploads|files)/.*\.php$ { deny all; }
location = /xmlrpc.php { deny all; }
# 静态资源浏览器缓存
location ~* \.(css|js|png|jpg|jpeg|gif|webp|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
location ~ \.php$ {
try_files $uri =404;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}
location ~ /\.ht { deny all; }
}
测试与调试
每次重新加载Nginx前,始终先测试配置:
# 测试配置语法 sudo nginx -t # 预期输出: # nginx: the configuration file /etc/nginx/nginx.conf syntax is ok # nginx: configuration file /etc/nginx/nginx.conf test is successful # 重新加载而不停止服务 sudo nginx -s reload # 或 sudo systemctl reload nginx
实时监控日志
# 访问日志 sudo tail -f /var/log/nginx/access.log # 错误日志(调试问题的关键) sudo tail -f /var/log/nginx/error.log
生产Nginx配置清单
- 设置
worker_processes auto和server_tokens off - 在sites-available/中为每个域名创建单独的服务器块
- 安装Let's Encrypt SSL并通过301重定向强制HTTPS
- 为文本、CSS、JS和SVG文件启用Gzip
- 添加安全标头:HSTS、X-Frame-Options、X-Content-Type-Options
- 为/wp-login.php和API端点实施速率限制
- 为WordPress启用FastCGI缓存提升性能
- 每次重新加载前始终运行
nginx -t
常见问题
sudo nginx -t测试所有配置语法。测试通过会显示\"syntax is ok\"和\"test is successful\"。然后使用sudo nginx -s reload应用更改而不停止服务。如果配置有误,Nginx不会重新加载,网站继续正常运行。try_files $uri $uri/ /index.php?$args;指令替代.htaccess重写规则。这实际上性能更好,因为每次请求不需要检查.htaccess文件是否存在。需要适合Nginx的VPS?
AsiaGB提供泰国和新加坡VPS,配备快速SSD存储,99%正常运行时间保障,支持Ubuntu 22.04/24.04。立即部署Nginx,快速启动您的项目。
查看VPS套餐 →