一、Nginx配置文件概述
Nginx作为高并发Web服务器,其核心配置文件nginx.conf采用模块化设计,通过分层结构实现灵活配置。典型配置文件包含全局块、events块、http块三大层级,其中http块可嵌套多个server块(虚拟主机配置)和upstream块(负载均衡配置)。
配置文件采用C风格注释(#开头),支持include指令实现配置拆分。例如:
include /etc/nginx/conf.d/*.conf;
这种设计使大型项目的配置管理更清晰,推荐将虚拟主机配置单独存放于conf.d目录。
二、核心参数详解
2.1 进程管理配置
worker_processes auto;
worker_processes定义工作进程数量,建议设置为CPU核心数(auto自动检测)。每个worker进程独立处理连接,通过多进程模型实现并发处理。
worker_rlimit_nofile 65535;
该参数提升单个worker可打开文件描述符数量,解决高并发场景下的”Too many open files”错误。需同步调整系统ulimit值:
ulimit -n 65535
2.2 事件驱动模型
events {worker_connections 10240;use epoll;multi_accept on;}
- worker_connections:单个worker最大连接数(含keepalive连接)
- use epoll:Linux下推荐的高性能事件模型
- multi_accept:允许worker一次接受所有新连接(默认关闭)
计算理论最大并发量:worker_processes * worker_connections / 2(每个连接占用读写两个文件描述符)
2.3 HTTP核心配置
2.3.1 基础参数
http {sendfile on;tcp_nopush on;keepalive_timeout 65;client_header_timeout 15;client_body_timeout 15;send_timeout 30;types_hash_max_size 2048;server_tokens off;}
- sendfile:零拷贝技术优化静态文件传输
- tcp_nopush:在sendfile启用时优化数据包发送
- keepalive_timeout:长连接保持时间(秒)
- server_tokens:隐藏Nginx版本号提升安全性
2.3.2 Gzip压缩配置
gzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;gzip_min_length 1k;gzip_buffers 4 16k;gzip_disable "MSIE [1-6]\.";
关键参数说明:
- comp_level:压缩级别(1-9),6为性能与压缩率的平衡点
- types:指定压缩的MIME类型,避免压缩已压缩资源(如图片)
- disable:针对旧版IE的兼容性处理
2.3.3 日志配置
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;error_log /var/log/nginx/error.log warn;
推荐使用JSON格式日志便于日志分析系统处理:
log_format json_combined escape=json'{''"time_local":"$time_iso8601",''"host":"$host",''"remote_addr":"$remote_addr",''"request":"$request",''"status": $status,''"bytes_sent": $body_bytes_sent,''"referer": "$http_referer",''"useragent": "$http_user_agent"''}';
三、虚拟主机配置
3.1 基础Server块
server {listen 80;server_name example.com www.example.com;root /var/www/html;index index.html index.php;location / {try_files $uri $uri/ /index.php?$query_string;}}
关键指令说明:
- server_name:支持通配符(*.example.com)和正则表达式(~^www\d+.example.com$)
- try_files:按顺序检查文件存在性,实现优雅的URL重写
3.2 反向代理配置
location /api/ {proxy_pass http://backend_servers;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 5s;proxy_read_timeout 30s;}
代理配置要点:
- 路径末尾斜杠决定是否去除匹配前缀(如
/api/与/api的区别) - X-Forwarded-For用于记录客户端真实IP
- 超时设置需根据后端服务响应时间调整
四、负载均衡配置
upstream backend_servers {server 192.168.1.10:8080 weight=5;server 192.168.1.11:8080 weight=3;server 192.168.1.12:8080 backup;least_conn;zone backend 64k;}
调度算法选择:
- 轮询(默认):按权重分配请求
- ip_hash:基于客户端IP的会话保持
- least_conn:最少连接数优先
- hash:自定义hash键(如$request_uri)
健康检查机制:
upstream backend_servers {server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;# ...}
五、FastCGI动态处理
PHP-FPM配置示例:
location ~ \.php$ {fastcgi_pass unix:/run/php/php7.4-fpm.sock;fastcgi_index index.php;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;include fastcgi_params;fastcgi_split_path_info ^(.+\.php)(/.+)$;fastcgi_param PATH_INFO $fastcgi_path_info;}
性能优化建议:
- 使用Unix Domain Socket替代TCP连接
- 调整FastCGI缓存参数:
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=PHP_CACHE:100m inactive=60m;
- 启用FastCGI缓存:
location ~ \.php$ {fastcgi_cache PHP_CACHE;fastcgi_cache_valid 200 301 302 1h;}
六、安全加固配置
6.1 基础防护
# 限制请求方法if ($request_method !~ ^(GET|HEAD|POST)$ ) {return 444;}# 防止非法文件上传location ~* (user|profile)\.php$ {deny all;}
6.2 速率限制
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;server {location /login/ {limit_req zone=one burst=5;}}
6.3 HTTPS强制跳转
server {listen 80;server_name example.com;return 301 https://$host$request_uri;}
七、性能监控与调优
7.1 状态监控
location /nginx_status {stub_status on;allow 127.0.0.1;deny all;}
访问/nginx_status可获取:
- Active connections:当前连接数
- requests:总请求数
- Reading/Writing/Waiting:连接状态分布
7.2 动态模块加载
现代Nginx支持动态模块:
load_module modules/ngx_http_geoip_module.so;
这种设计使功能扩展更灵活,减少内存占用。
八、配置验证与重载
配置修改后需进行语法检查:
nginx -t
平滑重载配置(不中断服务):
nginx -s reload
完整重启(慎用):
systemctl restart nginx
结语
Nginx配置的优化是一个持续过程,需要根据实际业务场景调整参数。建议通过监控工具持续观察QPS、响应时间、错误率等指标,结合AB测试等压测手段验证配置效果。对于大型分布式系统,可考虑结合容器编排工具实现Nginx配置的动态管理。