Nginx作为高性能的Web服务器和反向代理工具,其配置灵活性是关键优势。以下整理出实用配置与技巧,涵盖常见场景和优化方向:
# 全局配置
user nginx;
worker_processes auto; # 自动匹配CPU核心数
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024; # 单个worker最大连接数
use epoll; # Linux高性能事件模型
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"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
# Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
include /etc/nginx/conf.d/*.conf; # 加载子配置文件
}
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
try_files $uri $uri/ =404;
expires 30d; # 缓存控制
access_log off; # 静态资源可关闭日志
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
location /api/ {
proxy_pass http://backend_server;
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_connect_timeout 60s;
proxy_read_timeout 60s;
}
upstream backend {
least_conn; # 最少连接算法
server 10.0.0.1:8080 weight=3; # 权重
server 10.0.0.2:8080;
server 10.0.0.3:8080 backup; # 备用服务器
}
server {
location / {
proxy_pass http://backend;
}
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 强制HTTPS跳转
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
# IP白名单
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
# 速率限制(每秒1请求)
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
location /login/ {
limit_req zone=one burst=5;
}
Worker配置
worker_processes auto; # 自动匹配CPU核心
worker_rlimit_nofile 100000; # 提高文件描述符限制
缓存优化
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
}
长连接复用
upstream backend {
keepalive 32; # 连接池大小
}
日志优化
access_log off;
access_log /path/to/log combined buffer=32k flush=5s;
日志分析工具
tail -f /var/log/nginx/access.log | grep "500"
awk '{print $1}' access.log | sort | uniq -c | sort -nr
状态监控
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
输出示例:
Active connections: 3
server accepts handled requests
100 100 200
Reading: 0 Writing: 1 Waiting: 2
重定向测试
curl -I http://example.com # 检查HTTP头
nginx -t # 测试配置语法
WebSocket代理
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
GeoIP模块
geoip_country /usr/share/GeoIP/GeoIP.dat;
location / {
if ($geoip_country_code = CN) { return 403; }
}
A/B测试
split_clients "${remote_addr}AAA" $variant {
50% "/var/www/v1";
50% "/var/www/v2";
}
proxy_read_timeout
。rewrite
时注意last
和break
的区别。通过合理组合这些配置,可以构建高性能、安全的Nginx服务。建议根据实际需求逐步调整参数,并通过压测工具(如ab、wrk)验证效果。