Nginx 配置速查表

Nginx 最常用配置的快速参考,按功能分组

服务管理

nginx 启动 Nginx
nginx -s stop 快速停止
nginx -s quit 优雅停止
nginx -s reload 重载配置
nginx -t 测试配置语法
nginx -V 查看版本和编译参数
systemctl enable nginx 开机自启

基本配置

worker_processes auto; 工作进程数(自动匹配 CPU)
worker_connections 1024; 每进程最大连接数
sendfile on; 零拷贝文件传输
keepalive_timeout 65; 长连接超时
server_tokens off; 隐藏版本号
client_max_body_size 10m; 最大请求体

Server 块

listen 80; 监听 80 端口
listen 443 ssl http2; HTTPS + HTTP/2
server_name example.com; 域名匹配
root /var/www/html; 网站根目录
index index.html; 默认首页
return 301 https://...; 重定向

Location 匹配

location / { } 前缀匹配(最低优先级)
location = / { } 精确匹配(最高优先级)
location ^~ /static/ { } 前缀匹配(优先于正则)
location ~ \.php$ { } 正则匹配(区分大小写)
location ~* \.(jpg|png)$ { } 正则匹配(不区分大小写)
try_files $uri $uri/ /index.html; SPA 路由回退

反向代理

proxy_pass http://backend; 转发到后端
proxy_set_header Host $host; 传递原始 Host
proxy_set_header X-Real-IP $remote_addr; 传递真实 IP
proxy_connect_timeout 60s; 连接超时
proxy_read_timeout 90s; 读取超时
proxy_buffering off; 关闭缓冲(SSE/WebSocket)

SSL/HTTPS

ssl_certificate /path/cert.pem; 证书文件
ssl_certificate_key /path/key.pem; 私钥文件
ssl_protocols TLSv1.2 TLSv1.3; TLS 版本
certbot --nginx -d domain.com Let's Encrypt 获取证书
add_header Strict-Transport-Security ...; HSTS 安全头

性能优化

gzip on; 启用压缩
gzip_types text/css application/javascript; 压缩类型
expires 30d; 静态资源缓存
proxy_cache_path ... ; 反向代理缓存
open_file_cache max=1000; 文件描述符缓存