一、配置文件结构与指令体系
1.1 指令与上下文
Nginx 配置以声明式文本描述请求处理规则,由「指令 + 上下文」组成。
-
简单指令:
name parameter;以分号结尾 -
块指令:
name { ... }用花括号包裹,形成上下文(context) -
上下文层级:main(全局)> events / http > server > location
-
外层指令可被内层继承或覆盖;数组类指令(如
access_log、add_header)向下叠加
1.2 配置文件加载
-
主配置文件:
/etc/nginx/nginx.conf -
子配置包含:通过
include /etc/nginx/conf.d/*.conf;加载 -
默认 Web 根目录:
/usr/share/nginx/html
1.3 指令继承与覆盖规则
-
普通指令(如
root、index):内层覆盖外层 -
数组类指令(如
access_log、add_header):内层定义后外层不再继承;若内层未定义则继承外层
二、核心基础配置
本章给出各上下文的配置块示例,每个指令的作用、格式与取值说明见 nginx 配置 第一至第三章。
┌─────────────────────────────────────────────────────────────┐
│ 全局块(main block) │
│ user nginx; worker_processes auto; pid ...; │
│ 影响整个Nginx服务器的运行 │
├─────────────────────────────────────────────────────────────┤
│ events 块 │
│ worker_connections 1024; use epoll; │
│ 控制连接处理方式 │
├─────────────────────────────────────────────────────────────┤
│ http 块 │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ http全局配置(对所有网站生效) │ │
│ │ sendfile on; keepalive_timeout 65; ... │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ upstream 块(上游服务器) │ │
│ │ server 192.168.1.10:8080; │ │
│ │ 用于反向代理到后端服务 │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ server 块(网站1) │ │
│ │ listen 80; server_name a.com; root /var/www/a; │ │
│ │ ┌─────────────────────────────────────────────┐ │ │
│ │ │ location / { ... } │ │ │
│ │ │ location /images/ { ... } │ │ │
│ │ │ location ~ \.php$ { ... } │ │ │
│ │ └─────────────────────────────────────────────┘ │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ server 块(网站2) │ │
│ │ listen 443 ssl; server_name b.com; root /var/www/b;│ │
│ │ ┌─────────────────────────────────────────────┐ │ │
│ │ │ location / { ... } │ │ │
│ │ │ location /api/ { ... } │ │ │
│ │ └─────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
2.1 main 上下文(全局)
作用:控制 Nginx 进程本身的运行
worker_processes auto; # 工作进程数,通常等于 CPU 核数
worker_rlimit_nofile 65535; # 文件描述符上限
error_log /var/log/nginx/error.log warn; # 错误日志级别
pid /run/nginx.pid;
影响范围:整个 Nginx 服务器
2.2 events 上下文
作用:控制 Nginx 如何接受和处理连接
events {
worker_connections 1024; # 单个工作进程最大连接数
use epoll; # Linux 事件模型
multi_accept on; # 一次性接收多个连接
}
影响范围:整个 Nginx 服务器
2.3 http 上下文
作用:控制 HTTP 协议相关的所有配置
http {
include mime.types; # MIME 类型映射
default_type application/octet-stream;
sendfile on; # 零拷贝发送文件
tcp_nopush on; # 数据包聚合发送
keepalive_timeout 65; # 长连接超时(秒)
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log main;
include /etc/nginx/conf.d/*.conf;
}
影响范围:所有 HTTP 网站
log_format此处为简化示例,生产格式(含响应时间与后端字段)见 nginx 访问日志分析与在线监控 第十一章。
2.4 server 上下文(虚拟主机,在 http 内部)
作用:定义一个虚拟主机(一个网站或一个应用)
server {
listen 80; # 监听端口
server_name example.com www.example.com; # 虚拟主机名
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404; # 依次尝试 文件 -> 目录 -> 404
}
}
影响范围:该域名/端口的所有请求
2.5 location 匹配规则(在 server 内部)
作用:定义不同 URL 路径的处理方式
| 修饰符 | 含义 | 示例 |
|---|---|---|
= | 精确匹配 | location = /favicon.ico |
^~ | 前缀匹配,匹配后不再走正则 | location ^~ /static/ |
~ | 区分大小写正则 | location ~ \.php$ |
~* | 不区分大小写正则 | location ~* \.(jpg\|png)$ |
| 无修饰符 | 普通前缀匹配 | location /api/ |
匹配优先级:= > ^~ > 正则(~ / ~*)> 普通前缀
匹配符号与优先级速查见 Nginx 配置 第六章。
2.6 静态资源配置
server {
listen 80;
server_name static.example.com;
root /usr/share/nginx/html;
location / {
try_files $uri $uri/ /index.html; # 单页应用回退
}
location ~* \.(jpg|png|gif|ico|css|js)$ {
expires 30d; # 客户端缓存 30 天
add_header Cache-Control "public";
access_log off; # 静态资源不记录访问日志
}
location ~ /\. {
deny all; # 禁止访问隐藏文件
}
}
影响范围:匹配该 URL 路径的请求
三、反向代理与负载均衡
3.1 反向代理基础
location /api/ {
proxy_pass http://127.0.0.1:8080/; # 末尾斜杠影响 URI 替换
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_connect_timeout 5s; # 连接后端超时
proxy_send_timeout 60s; # 向后端发送超时
proxy_read_timeout 60s; # 读取后端响应超时
}
URI 替换规则:
-
proxy_pass http://backend/(带路径):/api/foo->/foo -
proxy_pass http://backend(无路径):/api/foo->/api/foo
3.2 负载均衡
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;
# 权重(按比例分配)
# server 192.168.1.10:8080 weight=3;
# server 192.168.1.11:8080 weight=1;
# ip_hash(基于客户端 IP 的会话保持)
# ip_hash;
# least_conn(转发到当前连接数最少的节点)
# least_conn;
}
server {
location / {
proxy_pass http://backend; # 引用 upstream 名称
}
}
3.3 健康检查
被动检查(内置):节点请求失败达到 max_fails 次后,在 fail_timeout 时间内不再转发。
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
# 标记为永久不可用(用于灰度下线)
# server 192.168.1.11:8080 down;
# 备用节点(主节点全不可用时启用)
# server 192.168.1.12:8080 backup;
}
主动检查:需 nginx plus 或第三方模块 nginx_upstream_check_module,开源版不支持。
weight/backup/down等 upstream server 附加参数说明见 nginx 配置 第四章。
3.4 WebSocket 代理
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # 长连接保持
}
四、HTTPS 与安全
4.1 SSL/TLS 配置
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/server.crt; # 证书
ssl_certificate_key /etc/nginx/ssl/server.key; # 私钥
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;
ssl_session_tickets off;
# HSTS:强制浏览器后续走 HTTPS
add_header Strict-Transport-Security "max-age=31536000" always;
}
4.2 HTTP 跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri; # 301 永久重定向
}
4.3 rewrite 重写
# 将 /old/xxx 永久重定向到 /new/xxx
location /old {
rewrite ^/old/(.*)$ /new/$1 permanent; # permanent=301, redirect=302
}
# 域名跳转
server {
server_name old.com;
rewrite ^/(.*)$ https://new.com/$1 permanent;
}
4.4 访问控制(IP)
location /admin {
allow 192.168.1.0/24; # 允许网段
allow 10.0.0.0/8;
deny all; # 拒绝其他
}
location ~ \.sql$ {
deny all; # 禁止访问敏感文件
}
4.5 Basic 认证
location /protected {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
生成密码文件:htpasswd -c /etc/nginx/.htpasswd username(需 apache2-utils)
4.6 限流(请求速率 + 并发连接)
http {
# 定义限流区:按客户端 IP,速率 10 请求/秒
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
# 定义并发连接限流区
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}
server {
location /api/ {
limit_req zone=req_limit burst=20 nodelay; # 突发缓冲 20,不延迟
limit_conn conn_limit 10; # 单 IP 最大 10 并发
limit_req_status 429; # 触发限流的返回码
limit_conn_status 429;
proxy_pass http://backend;
}
}
参数说明:
-
limit_req_zone ... rate=10r/s:平均速率 10 请求/秒 -
burst=20:允许 20 个突发请求排队 -
nodelay:突发请求立即处理而不排队等待(超出立即拒绝)
4.7 请求体大小限制
http {
client_max_body_size 20m; # 上传文件上限,超出返回 413
client_body_timeout 60s; # 请求体接收超时
}
五、性能与缓存
5.1 gzip 压缩
http {
gzip on;
gzip_min_length 1024; # 小于 1KB 不压缩
gzip_comp_level 6; # 压缩级别 1-9
gzip_types text/plain text/css application/json application/javascript
application/xml text/javascript image/svg+xml;
gzip_vary on; # 追加 Vary: Accept-Encoding
gzip_proxied any; # 代理请求也压缩
}
5.2 proxy 缓存(反向代理结果缓存)
http {
proxy_cache_path /var/cache/nginx/proxy
levels=1:2
keys_zone=proxy_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
}
server {
location / {
proxy_cache proxy_cache;
proxy_cache_valid 200 304 10m; # 200/304 缓存 10 分钟
proxy_cache_valid 404 1m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status; # 观察命中状态
proxy_pass http://backend;
}
}
$upstream_cache_status 取值:MISS / HIT / EXPIRED / BYPASS / STALE
5.3 fastcgi 缓存
http {
fastcgi_cache_path /var/cache/nginx/fastcgi
levels=1:2
keys_zone=fcgi_cache:10m
max_size=1g
inactive=60m;
}
location ~ \.php$ {
fastcgi_cache fcgi_cache;
fastcgi_cache_valid 200 10m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
5.4 超时与连接调优
http {
client_header_timeout 30s; # 请求头接收超时
client_body_timeout 60s; # 请求体接收超时
send_timeout 60s; # 响应发送超时
keepalive_timeout 65s; # 长连接空闲超时
keepalive_requests 1000; # 单条长连接最大请求数
reset_timedout_connection on;
}
5.5 浏览器缓存控制
location ~* \.(jpg|png|gif|css|js|woff2)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location ~ \.(html)$ {
add_header Cache-Control "no-cache"; # HTML 不缓存
}
六、验证手段
6.1 配置语法检查
nginx -t # 检查配置语法,不重载
nginx -T # 输出完整生效配置(含 include 展开)
nginx -t -c /path/to/nginx.conf # 指定配置文件检查
6.2 生效与进程控制
nginx -s reload # 平滑重载(修改配置后生效)
nginx -s stop # 快速停止
nginx -s quit # 优雅停止(处理完当前连接)
nginx -s reopen # 重新打开日志文件(日志切割用)
6.3 请求行为验证
# 查看响应头与状态码
curl -I http://localhost/
# 指定 Host(虚拟主机路由验证)
curl -H "Host: example.com" http://localhost/
# 验证 HTTPS
curl -k https://localhost/ # 跳过证书校验
curl -v --resolve example.com:443:127.0.0.1 https://example.com/
# 验证反向代理转发
curl -I http://localhost/api/
# 验证重写/重定向
curl -I http://localhost/old/path # 查看 Location 头
# 验证限流(连续发请求触发 429)
for i in $(seq 1 30); do curl -s -o /dev/null -w "%{http_code}\n" http://localhost/api/; done
# 验证缓存命中
curl -I -s http://localhost/ | grep X-Cache
6.4 日志观测
# 访问日志路径
/var/log/nginx/access.log
# 错误日志路径
/var/log/nginx/error.log
# 实时查看
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
# 统计状态码分布
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c
6.5 日志分析与在线监控
日志格式自定义、JSON 结构化日志、命令行分析、GoAccess / ELK / Loki 方案、Prometheus 指标采集、Grafana 看板与告警,详见 nginx 访问日志分析与在线监控。
6.6 状态监控页
location /nginx_status {
stub_status on; # 需编译模块 --with-http_stub_status_module
access_log off;
allow 127.0.0.1;
deny all;
}
访问 http://localhost/nginx_status,输出字段含义:
-
active connections:当前活跃连接数 -
accepts:已接受连接总数 -
handled:已处理连接总数 -
requests:已处理请求总数 -
Reading:正在读取请求头的连接数 -
Writing:正在返回响应的连接数 -
Waiting:空闲等待中的连接数
6.7 常见报错排查
| 报错/状态 | 原因 | 处理 |
|---|---|---|
nginx: [emerg] bind() failed (98) | 端口被占用 | 检查 netstat -tlnp \| grep :80 |
nginx: [emerg] "root" directive is duplicate | 指令在同级重复定义 | 删除多余指令 |
nginx: [emerg] unknown directive | 指令拼写错误或模块未加载 | 检查拼写与编译参数 |
404 Not Found | 资源路径或 try_files 配置问题 | 检查 root、index、文件存在性 |
403 Forbidden | 文件无权限或 autoindex off | 检查文件权限、index 是否存在 |
502 Bad Gateway | 后端服务不可达或拒绝连接 | 检查后端进程、端口、proxy_pass |
504 Gateway Timeout | 后端响应超时 | 调大 proxy_read_timeout 或排查后端性能 |
413 Request Entity Too Large | 请求体超过上限 | 调大 client_max_body_size |
429 Too Many Requests | 限流触发 | 确认 limit_req 是否符合预期 |
七、Docker 环境适配
7.1 配置文件挂载
# 将宿主机配置挂载进容器
docker run -d \
-p 80:80 -p 443:443 \
-v /host/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /host/conf.d:/etc/nginx/conf.d:ro \
-v /host/html:/usr/share/nginx/html:ro \
-v /host/logs:/var/log/nginx \
-v /host/cache:/var/cache/nginx \
--name nginx nginx:stable
7.2 容器内执行命令
docker exec -it nginx nginx -t # 语法检查
docker exec -it nginx nginx -s reload # 重载配置
docker exec -it nginx cat /etc/nginx/nginx.conf
docker logs -f nginx # 查看容器标准输出日志
7.3 修改配置后生效
# 方式一:进入容器重载
docker exec -it nginx nginx -s reload
# 方式二:发送 HUP 信号
docker kill -s HUP nginx
# 方式三:重启容器(配置已挂载时也适用,但会断开连接)
docker restart nginx
7.4 默认配置文件位置(容器内)
| 用途 | 路径 |
|---|---|
| 主配置 | /etc/nginx/nginx.conf |
| 子配置目录 | /etc/nginx/conf.d/ |
| 默认站点 | /etc/nginx/conf.d/default.conf |
| Web 根目录 | /usr/share/nginx/html |
| MIME 映射 | /etc/nginx/mime.types |
| 访问日志 | /var/log/nginx/access.log |
| 错误日志 | /var/log/nginx/error.log |
八、变量参考
基础变量速查见 Nginx 配置 第七章,下表为含限流、缓存、upstream 维度的全量参考:
| 变量 | 含义 |
|---|---|
$remote_addr | 客户端 IP |
$binary_remote_addr | 客户端 IP 二进制形式(限流用) |
$remote_user | 已认证用户名 |
$time_local | 本地时间 |
$request | 原始请求行 |
$status | 响应状态码 |
$body_bytes_sent | 响应体字节数 |
$http_referer | Referer 头 |
$http_user_agent | User-Agent 头 |
$host | 请求 Host 头或 server_name |
$scheme | http 或 https |
$request_uri | 原始请求 URI(含参数) |
$uri | 规范化后的 URI |
$args | 请求参数 |
$document_root | 当前 root 指令值 |
$proxy_add_x_forwarded_for | 拼接后的 X-Forwarded-For |
$upstream_cache_status | proxy 缓存命中状态 |
$upstream_addr | 实际转发的后端地址 |
$upstream_response_time | 后端响应耗时 |