经常有人贴一份 Nginx 配置问「这样行不行」。我把线上跑了半年的模板整理出来,每项都说明原因。
基础段
server {
listen 443 ssl http2;
server_name www.example.com;
root /www/wwwroot/example/public;
index index.php index.html;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}
http2 放 listen 里,多个域名共用一个 server 时只写一次
- 只开 TLS1.2/1.3,1.0/1.1 有兼容风险且不安全
- session cache 10m 大约能缓存 4 万个会话,个人站够用
压缩
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml;
gzip_vary on;
comp_level 5 是性价比最高的档位,9 会明显吃 CPU 但只多压几个百分点。gzip_min_length 1024 避免小文件压缩后反而更大。
静态资源缓存
location ~* \.(jpg|jpeg|png|gif|webp|svg|css|js|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
带 hash 的文件(如 app.8f3a.js)可以设一年,不带 hash 的设 30 天。immutable 让浏览器不再发条件请求。
反向代理超时
proxy_connect_timeout 3s;
proxy_send_timeout 10s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503;
超时别设太长,否则慢请求会把 worker 占满。10 秒对普通页面足够,接口类可以设 30 秒但要单独 location。
隐藏文件与备份
location ~ /\.(git|env|svn) { deny all; }
location ~* \.(sql|bak|log|tar|gz|zip)$ { deny all; }
这条是防止源码和备份被直接下载,出过太多事故。
日志
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
加了 request_time 和 upstream_response_time,排查慢请求时能直接看出是 Nginx 层还是后端慢。
检查
改完必跑:
nginx -t && nginx -s reload
reload 是平滑的,不会断连接,别用 restart。