一、环境准备与编译安装
1.1 系统基础环境配置
在Ubuntu/Debian系统上执行以下操作完成依赖安装:
# 更新软件包索引并安装编译工具链sudo apt update && sudo apt install -y \build-essential \libpcre3 libpcre3-dev \zlib1g zlib1g-dev \libssl-dev \curl wget git
建议配置国内镜像源加速下载过程,可通过修改/etc/apt/sources.list文件实现。对于CentOS/RHEL系统,需使用yum groupinstall "Development Tools"安装开发工具组。
1.2 源码编译安装流程
创建自动化安装脚本install_nginx.sh,包含以下关键步骤:
#!/bin/bash# 创建专用用户组sudo groupadd -r nginx && sudo useradd -r -g nginx -s /sbin/nologin nginx# 下载解压源码包(示例使用1.24.0版本)cd /tmpwget http://nginx.org/download/nginx-1.24.0.tar.gztar zxvf nginx-*.tar.gz && cd nginx-*# 配置编译参数(生产环境建议添加--with-debug)./configure \--prefix=/usr/local/nginx \--user=nginx \--group=nginx \--with-http_ssl_module \--with-http_v2_module \--with-http_realip_module \--with-stream \--with-threadsmake -j$(nproc) && sudo make install
关键参数说明:
--with-stream:启用四层代理功能(TCP/UDP)--with-threads:优化高并发场景性能--with-debug:开启调试日志(生产环境慎用)
1.3 systemd服务管理
创建服务管理文件/etc/systemd/system/nginx.service:
[Unit]Description=High performance web serverAfter=network.target[Service]Type=forkingPIDFile=/usr/local/nginx/logs/nginx.pidExecStartPre=/usr/local/nginx/sbin/nginx -tExecStart=/usr/local/nginx/sbin/nginxExecReload=/usr/local/nginx/sbin/nginx -s reloadExecStop=/usr/local/nginx/sbin/nginx -s quitTimeoutStopSec=5KillMode=processRestart=on-failure[Install]WantedBy=multi-user.target
执行以下命令启用服务:
sudo systemctl daemon-reloadsudo systemctl enable --now nginx
二、静态资源服务配置
2.1 目录结构规划
推荐采用以下标准目录布局:
/var/www/└── static-site/├── html/ # 静态文件根目录├── logs/ # 访问日志├── conf.d/ # 站点配置片段└── certs/ # SSL证书存储
权限设置最佳实践:
sudo chown -R nginx:nginx /var/www/static-sitesudo chmod -R 750 /var/www/static-sitefind /var/www/static-site -type d -exec chmod 750 {} \;
2.2 基础配置模板
创建配置文件/etc/nginx/conf.d/static-site.conf:
server {listen 80;server_name example.com www.example.com;root /var/www/static-site/html;index index.html index.htm;access_log /var/www/static-site/logs/access.log combined;error_log /var/www/static-site/logs/error.log warn;location / {try_files $uri $uri/ =404;expires 30d;add_header Cache-Control "public";}# 禁止访问敏感文件location ~ /(\.ht|README|LICENSE|backup) {deny all;return 403;}}
关键优化点:
expires指令设置浏览器缓存try_files实现优雅的404处理- 正则匹配保护敏感文件
三、HTTPS与性能优化
3.1 SSL证书配置
使用Let’s Encrypt免费证书的自动化部署方案:
# 安装certbot工具sudo apt install -y certbot python3-certbot-nginx# 获取证书(需提前解析DNS)sudo certbot --nginx -d example.com -d www.example.com \--email admin@example.com --agree-tos --no-eff-email
生成的配置会自动追加到对应server块,典型SSL配置如下:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;
3.2 性能调优参数
主配置文件nginx.conf的http块优化建议:
http {# 全局优化sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;keepalive_requests 1000;types_hash_max_size 2048;client_max_body_size 20m;# 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;# 缓冲区设置client_body_buffer_size 128k;client_header_buffer_size 16k;large_client_header_buffers 4 32k;# 包含子配置include /etc/nginx/conf.d/*.conf;}
四、负载均衡集群部署
4.1 四层负载均衡配置
使用stream模块实现TCP代理(如MySQL集群):
stream {upstream mysql_backend {server 10.0.0.1:3306;server 10.0.0.2:3306;server 10.0.0.3:3306;}server {listen 3306;proxy_pass mysql_backend;proxy_timeout 3s;proxy_connect_timeout 1s;}}
4.2 七层负载均衡策略
HTTP应用的负载均衡配置示例:
upstream web_backend {# 权重轮询(默认)server 10.0.0.4:80 weight=5;server 10.0.0.5:80 weight=3;# IP哈希(会话保持)# ip_hash;# 最少连接# least_conn;}server {listen 80;location / {proxy_pass http://web_backend;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;proxy_send_timeout 60s;}}
4.3 健康检查配置
通过max_fails和fail_timeout实现故障自动隔离:
upstream api_backend {server 10.0.0.6:8080 max_fails=3 fail_timeout=30s;server 10.0.0.7:8080 max_fails=3 fail_timeout=30s;}
五、监控与维护
5.1 状态监控接口
启用stub_status模块获取实时指标:
server {listen 8080;server_name status.example.com;allow 10.0.0.0/8;deny all;location /nginx_status {stub_status on;access_log off;}}
访问http://status.example.com/nginx_status可获取:
- 活动连接数
- 每秒请求数
- 读写状态分布
5.2 日志分析方案
推荐使用ELK或Loki+Grafana构建日志分析平台,基础日志轮转配置:
# 创建日志轮转配置cat > /etc/logrotate.d/nginx <<EOF/var/www/*/logs/*.log {dailymissingokrotate 14compressdelaycompressnotifemptycreate 0640 nginx admsharedscriptspostrotateif [ -f /usr/local/nginx/logs/nginx.pid ]; thenkill -USR1 `cat /usr/local/nginx/logs/nginx.pid`fiendscript}EOF
六、常见问题排查
- 502 Bad Gateway:检查后端服务是否正常运行,代理超时设置是否合理
- 连接数过高:调整
worker_connections(默认512)和worker_rlimit_nofile - SSL握手失败:验证证书链完整性,检查协议版本支持
- 静态文件403:确认目录权限和SELinux上下文(
chcon -Rt httpd_sys_content_t /var/www)
通过本文提供的完整配置方案,运维人员可快速构建从单机服务到集群架构的Nginx应用体系。建议结合具体业务场景进行参数调优,并定期进行安全审计与性能基准测试。