Appearance
Nginx 最佳实践
本章总结了Nginx配置和使用的最佳实践,帮助您构建高性能、安全、稳定的Web服务。
配置结构最佳实践
模块化配置
将配置文件拆分为多个模块,便于管理和维护:
# /etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-available/*;
配置文件组织
创建独立的配置文件用于不同功能:
security.conf- 安全相关配置performance.conf- 性能优化配置cache.conf- 缓存配置ssl.conf- SSL相关配置
安全最佳实践
隐藏服务器信息
server_tokens off;
# 自定义错误页面
error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 426 /40x.html;
error_page 500 501 502 503 504 505 506 507 508 509 510 511 /50x.html;
SSL/TLS配置最佳实践
server {
listen 443 ssl http2;
server_name example.com;
# 使用强加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers off;
# 启用OCSP装订
ssl_stapling on;
ssl_stapling_verify on;
# 设置HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 其他安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
}
防止DDoS攻击
# 限制每个IP的连接数
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
server {
location / {
limit_conn conn_limit_per_ip 20;
limit_req zone=general burst=20 nodelay;
proxy_pass http://backend;
}
# 对敏感路径更严格的限制
location /login {
limit_req zone=general burst=5 nodelay;
proxy_pass http://backend;
}
}
性能最佳实践
工作进程优化
# 自动设置为CPU核心数
worker_processes auto;
worker_cpu_affinity auto;
# 设置worker连接数(通常为worker_processes * 1024)
events {
worker_connections 1024;
use epoll;
multi_accept on;
accept_mutex off;
}
静态文件服务优化
server {
# 启用高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 设置keepalive
keepalive_timeout 65;
keepalive_requests 100;
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|svg|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
}
缓存最佳实践
# 定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_bypass $http_cache_control;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
}
}
反向代理最佳实践
健康检查和负载均衡
upstream app_servers {
# 使用最少连接算法
least_conn;
# 配置服务器并设置健康检查参数
server app1.example.com:8080 max_fails=3 fail_timeout=30s;
server app2.example.com:8080 max_fails=3 fail_timeout=30s;
server app3.example.com:8080 max_fails=3 fail_timeout=30s;
# 备用服务器
server backup.example.com:8080 backup;
}
server {
location / {
proxy_pass http://app_servers;
# 设置适当的超时
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 传递客户端信息
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;
}
}
WebSocket支持
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket_backend {
server ws1.example.com:8080;
server ws2.example.com:8080;
}
server {
location /ws {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
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;
}
}
日志最佳实践
自定义日志格式
log_format detailed_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_x_forwarded_for" $request_time';
access_log /var/log/nginx/access.log detailed_log;
error_log /var/log/nginx/error.log warn;
访问日志优化
# 静态文件不记录访问日志
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
expires 1y;
}
监控和运维最佳实践
状态监控
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 10.0.0.0/8; # 内网IP段
deny all;
}
配置管理
- 使用版本控制管理配置文件
- 配置变更前先备份
- 使用
nginx -t验证配置 - 使用零停机重新加载配置
bash
# 验证配置
nginx -t
# 重新加载配置(零停机)
nginx -s reload
完整生产环境配置示例
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
accept_mutex off;
}
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" '
'$request_time';
access_log /var/log/nginx/access.log main;
# 基本优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
# 限制
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s;
# 缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;
# 包含站点配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
定期维护任务
- 定期检查日志文件大小
- 监控服务器性能指标
- 定期更新SSL证书
- 定期审查安全配置
- 定期更新Nginx版本
通过遵循这些最佳实践,可以确保Nginx服务器的高性能、高安全性和高可用性。