一、Nginx安装与基础环境准备
1.1 安装方式选择
Nginx支持源码编译与二进制包两种安装方式。对于生产环境,推荐使用操作系统官方仓库的稳定版本(如CentOS的yum install nginx或Ubuntu的apt install nginx),可自动处理依赖关系并简化维护流程。若需定制模块,则需下载源码包执行./configure --prefix=/usr/local/nginx --with-http_ssl_module等参数编译。
1.2 目录结构解析
安装完成后需熟悉关键目录:
/etc/nginx/:主配置文件目录/usr/share/nginx/html/:默认静态文件根目录/var/log/nginx/:日志存储目录/var/run/nginx.pid:进程ID文件
建议通过nginx -V命令验证安装模块,确保包含--with-http_ssl_module等必要模块。
二、核心配置模块详解
2.1 全局配置(main块)
user nginx; # 运行用户worker_processes auto; # 自动匹配CPU核心数error_log /var/log/nginx/error.log warn; # 日志级别建议生产环境用warnpid /var/run/nginx.pid;
关键参数说明:
worker_processes:建议设置为auto或物理核心数,例如4核CPU配置为worker_processes 4;worker_rlimit_nofile:可配合ulimit -n调整单个进程最大文件描述符数量,高并发场景建议设置为65535
2.2 事件驱动配置(events块)
events {worker_connections 4096; # 单进程最大连接数use epoll; # Linux系统推荐模型multi_accept on; # 启用批量连接接受}
性能调优要点:
- 理论最大连接数计算:
worker_processes * worker_connections - 针对百万级并发场景,需结合
sysctl.conf优化内核参数:net.ipv4.tcp_max_syn_backlog = 65536net.core.somaxconn = 65535
2.3 HTTP服务配置(http块)
2.3.1 MIME类型定义
通过include mime.types;加载200+种文件类型映射,也可自定义扩展:
types {application/wasm wasm; # 添加WebAssembly支持text/markdown md; # 添加Markdown支持}
2.3.2 日志格式定制
log_format json_combined escape=json '{''"time_local":"$time_local",''"remote_addr":"$remote_addr",''"request":"$request",''"status":"$status",''"request_time":$request_time,''"upstream_time":"$upstream_response_time"''}';access_log /var/log/nginx/access.log json_combined;
优势:结构化日志便于ELK等日志系统分析,escape=json参数可自动转义特殊字符。
三、虚拟主机与反向代理实战
3.1 基础虚拟主机配置
server {listen 80;server_name api.example.com;location / {root /usr/share/nginx/api;index index.html index.htm;}error_page 404 /404.html;error_page 500 502 503 504 /50x.html;}
关键配置项:
server_name支持通配符(如*.example.com)和正则表达式location优先级规则:=>^~>~>~*> 普通路径
3.2 反向代理高级配置
upstream backend_pool {zone backend_zone 64k; # 共享内存区域least_conn; # 最少连接调度算法server 10.0.0.1:8080 weight=3;server 10.0.0.2:8080;keepalive 32; # 长连接数}server {listen 443 ssl;server_name api.example.com;ssl_certificate /etc/nginx/ssl/api.crt;ssl_certificate_key /etc/nginx/ssl/api.key;location / {proxy_pass http://backend_pool;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_http_version 1.1;proxy_connect_timeout 60s;proxy_read_timeout 300s;}}
性能优化技巧:
- 启用
proxy_buffering off减少内存占用(适用于大文件下载场景) - 通过
proxy_cache配置静态资源缓存 - 使用
ssl_session_cache shared加速TLS握手
10m
四、安全加固与最佳实践
4.1 安全配置要点
# 隐藏Nginx版本信息server_tokens off;# 限制请求方法if ($request_method !~ ^(GET|HEAD|POST)$ ) {return 444;}# 防止目录遍历攻击autoindex off;# XSS防护add_header X-XSS-Protection "1; mode=block";
4.2 性能监控方案
- 基础监控:通过
stub_status模块获取实时状态location /nginx_status {stub_status on;allow 127.0.0.1;deny all;}
- 高级监控:集成Prometheus + Grafana方案
- 使用
nginx-prometheus-exporter暴露指标 - 关键监控指标:
nginx_connections_active:活跃连接数nginx_http_requests_total:请求总数nginx_upstream_response_time_seconds:后端响应时间
- 使用
五、故障排查与常见问题
5.1 启动失败排查流程
- 检查语法错误:
nginx -t - 查看错误日志:
tail -f /var/log/nginx/error.log - 验证端口占用:
netstat -tulnp | grep :80 - 检查SELinux状态:
getenforce(CentOS系统)
5.2 502 Bad Gateway问题
常见原因及解决方案:
- 后端服务崩溃:检查后端服务日志
- 连接超时:调整
proxy_connect_timeout参数 - 端口不匹配:确认
proxy_pass地址与后端服务监听端口一致
通过系统化的配置管理与性能优化,Nginx可轻松支撑百万级并发场景。建议结合具体业务需求,参考本文提供的配置模板进行定制化调整,并定期进行压力测试验证配置效果。对于超大规模部署场景,可考虑使用Nginx Plus或行业常见技术方案提供的动态配置管理能力。