Nginx 配置
概览
掌握 Nginx 配置,用于生产级别的 Web 服务器,反向代理,负载均衡,SSL 终止,缓存和 API 网关模式,以及高级性能调优。
使用场景
- 反向代理设置
- 后端服务之间的负载均衡
- SSL/TLS 终止
- HTTP/2 和 gRPC 支持
- 缓存和压缩
- 限流和 DDoS 保护
- URL 重写和路由
- API 网关功能
实施示例
1. 生产 Nginx 配置
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志记录
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format upstream_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log upstream_time buffer=32k flush=5s;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 20M;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml application/atom+xml image/svg+xml;
gzip_disable "msie6";
# 限流
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
limit_conn_zone $binary_remote_addr zone=connections:10m;
# 上游服务器
upstream backend {
least_conn;
server backend1.internal:8080 weight=5 max_fails=3 fail_timeout=30s;
server backend2.internal:8080 weight=5 max_fails=3 fail_timeout=30s;
server backend3.internal:8080 weight=3 max_fails=3 fail_timeout=30s;
keepalive 32;
}
upstream api_backend {
least_conn;
server api1.internal:3000;
server api2.internal:3000;
server api3.internal:3000;
keepalive 64;
}
# 缓存
proxy_cache_path /var/cache/nginx/general levels=1:2 keys_zone=general_cache:10m max_size=1g inactive=60m use_temp_path=off;
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:10m max_size=500m inactive=30m use_temp_path=off;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
2. HTTPS 服务器与负载均衡
# /etc/nginx/sites-available/myapp
server {
listen 80;
server_name myapp.com www.myapp.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name myapp.com www.myapp.com;
# SSL 配置
ssl_certificate /etc/ssl/certs/myapp.com.crt;
ssl_certificate_key /etc/ssl/private/myapp.com.key;
ssl_trusted_certificate /etc/ssl/certs/ca-bundle.crt;
# SSL 安全
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_stapling on;
ssl_stapling_verify on;
# 安全头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 根目录和日志记录
root /var/www/myapp;
access_log /var/log/nginx/myapp.access.log upstream_time;
error_log /var/log/nginx/myapp.error.log warn;
# 限流
limit_req zone=general burst=20 nodelay;
limit_conn connections 10;
# 代理设置
location / {
limit_req zone=general burst=20 nodelay;
proxy_pass http://backend;
proxy_http_version 1.1;
# 头信息
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_set_header Connection "";
# 超时
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓存
proxy_cache general_cache;
proxy_cache_valid 200 60m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
# API 端点不同缓存
location /api/ {
limit_req zone=api burst=10 nodelay;
proxy_pass http://api_backend;
proxy_http_version 1.1;
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;
# 仅缓存 GET 请求
proxy_cache api_cache;
proxy_cache_methods GET HEAD;
proxy_cache_valid 200 30m;
proxy_cache_key "$scheme$request_method$host$request_uri";
# 如果认证不缓存
proxy_no_cache $http_authorization;
}
# 静态文件长时间缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 健康检查端点
location /health {
access_log off;
return 200 "healthy
";
add_header Content-Type text/plain;
}
# 指标端点
location /metrics {
deny all;
}
}
3. Nginx 配置脚本
#!/bin/bash
# nginx-deploy.sh - 部署和验证 Nginx 配置
set -euo pipefail
echo "部署 Nginx 配置..."
# 测试配置
echo "测试 Nginx 配置..."
nginx -t
# 检查是否运行
if pgrep -x nginx > /dev/null; then
echo "重新加载 Nginx..."
systemctl reload nginx
else
echo "启动 Nginx..."
systemctl start nginx
fi
# 验证
echo "验证部署..."
sleep 2
# 检查服务状态
if systemctl is-active --quiet nginx; then
echo "Nginx 正在运行"
else
echo "错误:Nginx 启动失败"
systemctl status nginx
exit 1
fi
# 测试连通性
echo "测试端点..."
curl -k https://localhost/health || echo "警告:健康检查失败"
# 日志状态
echo "Nginx 配置部署成功"
journalctl -u nginx -n 20 --no-pager
4. Nginx 监控配置
# /etc/nginx/conf.d/monitoring.conf
server {
listen 127.0.0.1:8080;
server_name localhost;
# 监控 Stub 状态
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow ::1;
deny all;
}
# Prometheus 指标
location /metrics {
access_log off;
proxy_pass http://127.0.0.1:8081/metrics;
allow 127.0.0.1;
allow ::1;
deny all;
}
}
最佳实践
✅ 应该做
- 使用 HTTP/2 提升性能
- 启用 SSL/TLS 加密
- 实施适当的缓存策略
- 使用上游连接池
- 通过 stub_status 或 prometheus 监控
- 限流以防止滥用
- 添加安全头
- 使用 least_conn 负载均衡
- 将错误日志与访问日志分开
❌ 不应该做
- 禁用 gzip 压缩
- 使用弱 SSL 加密
- 缓存认证响应
- 允许直接访问后端
- 忽略上游健康检查
- 混合使用 HTTP 和 HTTPS 而不重定向
- 在生产中使用默认错误页面
- 缓存敏感用户数据
常用命令
nginx -t # 测试配置
systemctl reload nginx # 无中断重新加载
systemctl restart nginx # 完全重启
tail -f /var/log/nginx/access.log # 监控访问
curl localhost:8080/nginx_status # 检查状态