以下是一个关于Nginx全局配置的详细示例,涵盖基础架构、性能优化、安全防护、日志记录及监控维护等核心模块:
一、基础架构配置
# 主配置文件 nginx.conf
user nginx; # 运行用户
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 65535; # 最大文件描述符数
# 全局错误日志配置
error_log /var/log/nginx/global_error.log warn;
events {
worker_connections 65535; # 单进程最大连接数
use epoll; # Linux高效事件模型
multi_accept on; # 批量接受连接
accept_mutex_delay 50ms; # 避免惊群效应
}
# HTTP核心配置块
http {
# MIME类型配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 字符集配置
charset utf-8;
source_charset utf-8;
# 连接超时配置
keepalive_timeout 65s; # 长连接超时时间
keepalive_requests 1000; # 单个长连接最大请求数
client_header_timeout 15s; # 请求头读取超时
client_body_timeout 15s; # 请求体读取超时
send_timeout 30s; # 响应发送超时
# 客户端限制
client_max_body_size 100M; # 最大请求体大小
client_body_buffer_size 50M; # 请求体缓冲区大小
# 包含全局配置片段
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
# 四层负载均衡配置(TCP/UDP)
stream {
# 包含TCP/UDP服务配置
include /etc/nginx/stream.d/*.conf;
}
二、性能优化配置
1. 文件缓存配置
http {
# 开启文件描述符缓存
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 静态资源缓存
sendfile on; # 零拷贝传输
tcp_nopush on; # 合并小数据包发送
tcp_nodelay on; # 禁用Nagle算法
aio threads; # 异步文件I/O(需Linux内核支持)
}
2. 压缩传输配置
http {
# Brotli压缩(需编译支持)
brotli on;
brotli_comp_level 6;
brotli_types text/css text/javascript application/javascript image/svg+xml;
# GZIP压缩
gzip on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_proxied expired no-cache no-store private auth;
gzip_vary on; # 添加Vary头
}
3. 连接复用配置
http {
# 全局连接池配置
keepalive 32; # 保持32个长连接
keepalive_requests 1000; # 单个长连接最大请求数
keepalive_timeout 65s; # 长连接超时时间
# 后端连接池配置
upstream backend_pool {
zone backend_pool 64k;
server 10.0.0.10:8080;
keepalive 16; # 保持16个到后端的长连接
}
}
三、安全防护配置
1. 全局安全头
http {
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header Content-Security-Policy "default-src 'self';";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
}
2. 访问控制
http {
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
# 请求过滤
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
# 防盗链配置
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403 "Forbidden";
}
}
3. SSL/TLS配置
http {
ssl_protocols TLSv1.3; # 仅启用TLS 1.3
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256;
ssl_ecdh_curve secp384r1;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off; # 禁用会话票据(需配合OCSP)
ssl_stapling on; # 启用OCSP装订
ssl_stapling_verify on;
resolver 8.8.8.8 1.1.1.1 valid=300s;
}
四、日志记录配置
1. 访问日志
http {
log_format combined_json '{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":"$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time"'
'}';
access_log /var/log/nginx/access.log combined_json;
}
2. 错误日志
http {
error_log /var/log/nginx/error.log warn;
# 高级错误日志配置(需Lua模块)
log_by_lua_block {
if ngx.status >= 500 then
ngx.log(ngx.ERR, "Unhandled error: ", ngx.var.request)
end
}
}
五、监控维护配置
1. 状态监控
http {
server {
listen 8080;
server_name status.example.com;
location /nginx_status {
stub_status on; # 基础状态页
allow 192.168.1.0/24;
deny all;
}
location /prometheus_metrics {
# 集成Prometheus监控(需ngx_http_prometheus_module)
prometheus_metrics;
allow 192.168.1.0/24;
deny all;
}
}
}
2. 配置热加载
# 优雅重载配置(不中断服务)
nginx -s reload
# 完整重载流程(适合复杂变更)
nginx -t && systemctl reload nginx
六、高级功能配置
1. 动态模块加载
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;
2. 自定义模板
http {
# 自定义响应头模板
map $http_user_agent $custom_header {
default "Welcome to Example.com";
~*Chrome "Hello Chrome User!";
~*Firefox "Welcome Firefox User!";
}
add_header X-Custom-Greeting $custom_header;
}
3. 地理定位
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
CN yes;
US yes;
}
if ($allowed_country = no) {
return 403 "Service not available in your region";
}
}
七、配置验证与优化
-
语法检查
nginx -t -c /etc/nginx/nginx.conf
-
性能调优建议
- 调整
worker_processes
匹配CPU核心数 - 使用
sysctl -p
优化内核参数(如net.core.somaxconn
) - 定期执行
nginx -T
输出完整配置树
- 调整
-
安全加固措施
- 通过
ssl_dhparam
配置Diffie-Hellman参数 - 使用
ssl_certificate_key
加密私钥文件 - 定期轮换SSL证书和API密钥
- 通过
该配置示例实现了Nginx全局配置的核心功能,可根据实际需求扩展以下方向:
- 集成AWS/Azure云服务商特性
- 添加服务网格(Service Mesh)支持
- 实现自动化证书管理(通过Certbot)
- 配置分布式追踪(通过OpenTelemetry)
建议通过专业测试工具(如ab、wrk)验证配置效果,并结合APM工具(如Prometheus+Grafana)构建完整监控体系。