安装与目录
主流发行版直接装包:
apt install nginx # Debian/Ubuntu
yum install nginx # RHEL/CentOS
关键目录(RHEL 系):
/etc/nginx/nginx.conf:主配置/etc/nginx/conf.d/*.conf:站点片段/var/log/nginx/:日志/var/cache/nginx/:缓存
Docker 启动:
docker run --name nginx -d -p 80:80 \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /path/to/conf.d:/etc/nginx/conf.d:ro \
nginx:1.25-alpine
基本管理:
nginx -t # 检查配置
nginx -s reload # 热重载
nginx -V # 看编译参数 / 模块列表
location 匹配规则
location [=|^~|~|~*|/] /uri { ... }
| 前缀 | 含义 |
|---|---|
= | 精确匹配,优先级最高 |
^~ | 前缀匹配,不再走正则 |
~ | 大小写敏感正则 |
~* | 大小写不敏感正则 |
| 无前缀 | 普通前缀匹配 |
location = /favicon.ico { ... } # 精确
location ^~ /static/ { ... } # /static/ 前缀,不走正则
location ~* \.(png|jpg|jpeg)$ { ... } # 文件后缀
location /api/ { proxy_pass http://app; } # API 反代
反向代理
location /api/ {
proxy_pass http://127.0.0.1:8080/; # 注意尾斜杠会去掉 /api/
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_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 60s;
}
关键头:
X-Real-IP:客户端真实 IPX-Forwarded-For:链路 IP 链X-Forwarded-Proto:原始协议(http/https)
应用端要识别这些头,常见做法是 ASP.NET Core 里启用 UseForwardedHeaders。
负载均衡
upstream backend {
least_conn; # 调度算法
server 10.0.0.1:8080 weight=3 max_fails=2 fail_timeout=10s;
server 10.0.0.2:8080 weight=1;
server 10.0.0.3:8080 backup; # 备份
server 10.0.0.4:8080 down; # 维护
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
}
}
调度算法:
round-robin(默认):轮询weight=N:加权轮询ip_hash:按 IP 哈希(会话保持,但扩缩容会失效)least_conn:最少的连接数优先hash $key consistent:一致性哈希(Redis cluster 客户端常用)
URL 重写
location /old/ {
rewrite ^/old/(.*)$ /new/$1 permanent; # 301 永久重定向
}
location /temp/ {
rewrite ^/temp/(.*)$ /api/$1 last; # 内部跳转,地址栏不变
}
四种 flag:
| flag | 行为 |
|---|---|
last | 停止当前 location 处理,重新匹配下一轮 |
break | 停止 rewrite,继续当前 location 其余指令 |
redirect | 302 临时重定向 |
permanent | 301 永久重定向 |
HTTPS
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
add_header Strict-Transport-Security "max-age=31536000" always;
location / {
root /var/www/html;
}
}
HTTP → HTTPS 跳转:
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
Let's Encrypt 自动续签用 certbot。
缓存头与 expires
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2?)$ {
expires 7d; # 浏览器缓存 7 天
add_header Cache-Control "public, max-age=604800, immutable";
access_log off; # 静态不打日志
}
服务器端反向代理缓存:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=60m;
location /api/ {
proxy_pass http://backend;
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 5m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
}
X-Cache-Status 取值:HIT / MISS / EXPIRED / BYPASS / STALE。
限速与并发
# 全局限速:每个 IP 每秒 10 个请求
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
location /search {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
}
# 限制并发连接
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_conn conn_limit 20;
burst=20 nodelay 表示突发允许 20 个请求但立即执行,不排队。
动静分离
location /static/ {
alias /var/www/static/;
expires 30d;
try_files $uri =404;
}
location / {
proxy_pass http://backend;
}
alias 与 root 的区别:alias 会去掉 location 前缀再拼;root 是保留。
基础安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=()" always;
使用准则
location写规则前先决定"精确 / 前缀 / 正则"中的哪一种,不要把正则当通配用。- 反向代理一定要补齐
X-Real-IP/X-Forwarded-*三个头,应用端也要信任。 - 改完配置必须
nginx -t,再用reload,不要直接restart。 - 缓存目录要预留足够磁盘;超过
max_size会触发 LRU 淘汰。