Nginx 配置速查表
Nginx 常用配置速查:server、location、proxy_pass、upstream、ssl、gzip、rewrite 等高频指令与片段对照,附中文说明,运维部署与排障时快速查阅。
| 指令 / 片段 | 说明 |
|---|---|
| listen 80; | 监听端口(ssl 用 443 ssl) |
| server_name example.com; | 虚拟主机域名 |
| root /var/www; | 站点根目录 |
| index index.html; | 默认首页文件 |
| location / { } | 前缀路径匹配块 |
| location = /api { } | 精确匹配(优先级最高) |
| location ~ \.php$ { } | 正则匹配(区分大小写) |
| proxy_pass http://backend; | 反向代理到上游 |
| proxy_set_header Host $host; | 透传原始 Host 头 |
| upstream backend { } | 定义负载均衡后端组 |
| try_files $uri $uri/ =404; | 按序尝试文件,失败 404 |
| rewrite ^/old /new permanent; | 301 重写重定向 |
| return 301 https://$host$request_uri; | 强制 HTTP 跳 HTTPS |
| ssl_certificate /path/fullchain.pem; | SSL 证书链路径 |
| ssl_certificate_key /path/privkey.pem; | SSL 私钥路径 |
| gzip on; | 开启响应 gzip 压缩 |
| client_max_body_size 10m; | 限制请求体大小 |
| auth_basic "Restricted"; | 开启基础认证弹窗 |
| add_header Cache-Control "max-age=3600"; | 设置缓存响应头 |
| access_log /var/log/nginx/access.log; | 访问日志路径 |
| error_log /var/log/nginx/error.log; | 错误日志路径 |
| nginx -t | 测试配置文件语法 |
| nginx -s reload | 平滑重载配置(不中断) |
| nginx -s stop | 快速停止服务 |
常见问题
如何配置 Nginx 反向代理?
在 `server` 块里用 `location` 匹配路径,再用 `proxy_pass http://后端地址;` 转发;通常配合 `proxy_set_header Host $host;`、`proxy_set_header X-Real-IP $remote_addr;` 透传客户端信息。后端可以是 upstream 组实现负载均衡。
如何强制把所有 HTTP 请求跳转到 HTTPS?
用一个监听 80 的 `server` 块:`return 301 https://$host$request_uri;`,把明文请求 301 重定向到同域名 HTTPS;HTTPS 的 `server` 块再配置 `ssl_certificate` 与 `ssl_certificate_key`。
如何配置负载均衡(upstream)?
在 `http` 块定义 `upstream backend { server 10.0.0.1:8080; server 10.0.0.2:8080; }`,默认轮询;可加 `weight=` 调权重、`ip_hash;` 做会话保持;`location` 内 `proxy_pass http://backend;` 引用。
修改配置后如何让生效?
先 `nginx -t` 校验语法,确认无误后 `nginx -s reload` 平滑重载(已建连接不中断);若 Nginx 未运行则用 `nginx` 启动。`reload` 不会丢流量,优于 `stop` 再启动。