1. Nginx基础环境准备(CentOS 7.9)
1.1 系统环境检查
在CentOS 7.9上部署Nginx前,建议先执行cat /etc/redhat-release确认系统版本。我遇到过不少案例因为系统版本不匹配导致依赖库冲突,特别是当使用第三方YUM源时。
内存和磁盘空间检查同样重要:
bash复制free -h # 查看内存情况
df -h # 查看磁盘空间
注意:生产环境建议至少2GB内存,/var目录保留10GB以上空间用于日志存储
1.2 依赖安装
EPEL仓库是必须的,但要注意网络环境:
bash复制yum install -y epel-release
yum makecache fast
基础依赖包建议这样安装:
bash复制yum groupinstall -y "Development Tools"
yum install -y pcre-devel zlib-devel openssl-devel
这里选择源码编译常用的开发组而非最小化安装,是因为后期调试和模块扩展时会用到这些工具链。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. Nginx安装与基础命令
2.1 两种安装方式对比
YUM安装(推荐新手):
bash复制yum install -y nginx
systemctl enable nginx
优势是自动处理依赖和服务管理,但版本可能较旧(默认1.20.x)
源码编译安装:
wget复制tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make && make install
适合需要定制模块或特定版本的情况,编译参数根据实际需求调整。
2.2 核心服务命令
bash复制systemctl start nginx # 启动
systemctl stop nginx # 停止
systemctl restart nginx # 重启(会中断连接)
systemctl reload nginx # 热重载(推荐生产环境使用)
nginx -t # 测试配置文件语法
nginx -V # 查看编译参数
踩坑记录:reload和restart的区别非常重要。有次在线上直接restart导致大量502错误,后来改用reload就平滑多了。
3. 关键配置解析
3.1 主配置文件结构
/etc/nginx/nginx.conf 主要包含:
nginx复制user nginx; # 运行用户
worker_processes auto; # 自动匹配CPU核心数
events {
worker_connections 1024; # 单个worker连接数
}
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;
include /etc/nginx/conf.d/*.conf; # 包含子配置
}
3.2 虚拟主机配置示例
在/etc/nginx/conf.d/下新建example.conf:
nginx复制server {
listen 80;
server_name example.com;
location / {
root /usr/share/nginx/html;
index index.html;
}
location /api/ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
3.3 性能调优参数
nginx复制keepalive_timeout 65; # TCP连接保持时间
gzip on; # 开启压缩
gzip_types text/plain application/xml; # 指定压缩类型
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
4. 实战问题排查
4.1 常见错误代码处理
502 Bad Gateway:
- 检查后端服务是否存活
netstat -tulnp | grep 后端端口 - 查看Nginx错误日志
tail -50 /var/log/nginx/error.log - 调整proxy连接参数:
nginx复制proxy_connect_timeout 60s;
proxy_read_timeout 60s;
413 Request Entity Too Large:
nginx复制client_max_body_size 20M; # 在http或server块中添加
4.2 日志分析技巧
实时监控访问日志:
bash复制tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
统计HTTP状态码分布:
bash复制awk '{print $9}' access.log | sort | uniq -c | sort -rn
4.3 安全加固建议
- 隐藏Nginx版本号:
nginx复制server_tokens off;
- 禁用不必要的方法:
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
- 限制敏感文件访问:
nginx复制location ~* \.(env|git|svn|htaccess) {
deny all;
}
5. 高级功能实现
5.1 负载均衡配置
nginx复制upstream backend {
server 192.168.1.10:8080 weight=5;
server 192.168.1.11:8080;
server 192.168.1.12:8080 backup;
}
server {
location / {
proxy_pass http://backend;
health_check interval=10 fails=3 passes=2;
}
}
5.2 HTTPS配置
使用Let's Encrypt证书示例:
nginx复制server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 启用HTTP/2
listen 443 http2;
# 安全协议配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
}
5.3 动静分离实践
nginx复制server {
location /static/ {
alias /data/static/;
expires max;
}
location / {
proxy_pass http://app_server;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
}
}
6. 维护与监控
6.1 日志轮转配置
/etc/logrotate.d/nginx 示例:
bash复制/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
6.2 状态监控
启用stub_status模块:
nginx复制location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
输出示例:
code复制Active connections: 3
server accepts handled requests
10 10 20
Reading: 0 Writing: 1 Waiting: 2
6.3 性能测试工具
使用ab进行压力测试:
bash复制ab -n 1000 -c 100 http://test.com/
关键指标解读:
- Requests per second: 每秒处理请求数
- Time per request: 单个请求平均耗时
- Transfer rate: 网络吞吐量
最后分享一个排查连接数问题的技巧:当发现worker_connections are not enough错误时,除了调整worker_connections参数,更要检查是否真的需要这么多连接,可能是客户端没有正确关闭连接导致的。我通常会用netstat -anp | grep nginx | wc -l实时监控实际连接数。
