Nginx全场景配置指南:从单机部署到高可用架构

一、环境准备与编译安装

1.1 系统基础环境配置

在Ubuntu/Debian系统上执行以下操作完成依赖安装:

  1. # 更新软件包索引并安装编译工具链
  2. sudo apt update && sudo apt install -y \
  3. build-essential \
  4. libpcre3 libpcre3-dev \
  5. zlib1g zlib1g-dev \
  6. libssl-dev \
  7. curl wget git

建议配置国内镜像源加速下载过程,可通过修改/etc/apt/sources.list文件实现。对于CentOS/RHEL系统,需使用yum groupinstall "Development Tools"安装开发工具组。

1.2 源码编译安装流程

创建自动化安装脚本install_nginx.sh,包含以下关键步骤:

  1. #!/bin/bash
  2. # 创建专用用户组
  3. sudo groupadd -r nginx && sudo useradd -r -g nginx -s /sbin/nologin nginx
  4. # 下载解压源码包(示例使用1.24.0版本)
  5. cd /tmp
  6. wget http://nginx.org/download/nginx-1.24.0.tar.gz
  7. tar zxvf nginx-*.tar.gz && cd nginx-*
  8. # 配置编译参数(生产环境建议添加--with-debug)
  9. ./configure \
  10. --prefix=/usr/local/nginx \
  11. --user=nginx \
  12. --group=nginx \
  13. --with-http_ssl_module \
  14. --with-http_v2_module \
  15. --with-http_realip_module \
  16. --with-stream \
  17. --with-threads
  18. make -j$(nproc) && sudo make install

关键参数说明:

  • --with-stream:启用四层代理功能(TCP/UDP)
  • --with-threads:优化高并发场景性能
  • --with-debug:开启调试日志(生产环境慎用)

1.3 systemd服务管理

创建服务管理文件/etc/systemd/system/nginx.service

  1. [Unit]
  2. Description=High performance web server
  3. After=network.target
  4. [Service]
  5. Type=forking
  6. PIDFile=/usr/local/nginx/logs/nginx.pid
  7. ExecStartPre=/usr/local/nginx/sbin/nginx -t
  8. ExecStart=/usr/local/nginx/sbin/nginx
  9. ExecReload=/usr/local/nginx/sbin/nginx -s reload
  10. ExecStop=/usr/local/nginx/sbin/nginx -s quit
  11. TimeoutStopSec=5
  12. KillMode=process
  13. Restart=on-failure
  14. [Install]
  15. WantedBy=multi-user.target

执行以下命令启用服务:

  1. sudo systemctl daemon-reload
  2. sudo systemctl enable --now nginx

二、静态资源服务配置

2.1 目录结构规划

推荐采用以下标准目录布局:

  1. /var/www/
  2. └── static-site/
  3. ├── html/ # 静态文件根目录
  4. ├── logs/ # 访问日志
  5. ├── conf.d/ # 站点配置片段
  6. └── certs/ # SSL证书存储

权限设置最佳实践:

  1. sudo chown -R nginx:nginx /var/www/static-site
  2. sudo chmod -R 750 /var/www/static-site
  3. find /var/www/static-site -type d -exec chmod 750 {} \;

2.2 基础配置模板

创建配置文件/etc/nginx/conf.d/static-site.conf

  1. server {
  2. listen 80;
  3. server_name example.com www.example.com;
  4. root /var/www/static-site/html;
  5. index index.html index.htm;
  6. access_log /var/www/static-site/logs/access.log combined;
  7. error_log /var/www/static-site/logs/error.log warn;
  8. location / {
  9. try_files $uri $uri/ =404;
  10. expires 30d;
  11. add_header Cache-Control "public";
  12. }
  13. # 禁止访问敏感文件
  14. location ~ /(\.ht|README|LICENSE|backup) {
  15. deny all;
  16. return 403;
  17. }
  18. }

关键优化点:

  • expires指令设置浏览器缓存
  • try_files实现优雅的404处理
  • 正则匹配保护敏感文件

三、HTTPS与性能优化

3.1 SSL证书配置

使用Let’s Encrypt免费证书的自动化部署方案:

  1. # 安装certbot工具
  2. sudo apt install -y certbot python3-certbot-nginx
  3. # 获取证书(需提前解析DNS)
  4. sudo certbot --nginx -d example.com -d www.example.com \
  5. --email admin@example.com --agree-tos --no-eff-email

生成的配置会自动追加到对应server块,典型SSL配置如下:

  1. ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  2. ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  3. ssl_protocols TLSv1.2 TLSv1.3;
  4. ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
  5. ssl_prefer_server_ciphers on;
  6. ssl_session_cache shared:SSL:10m;
  7. ssl_session_timeout 10m;

3.2 性能调优参数

主配置文件nginx.conf的http块优化建议:

  1. http {
  2. # 全局优化
  3. sendfile on;
  4. tcp_nopush on;
  5. tcp_nodelay on;
  6. keepalive_timeout 65;
  7. keepalive_requests 1000;
  8. types_hash_max_size 2048;
  9. client_max_body_size 20m;
  10. # Gzip压缩
  11. gzip on;
  12. gzip_vary on;
  13. gzip_proxied any;
  14. gzip_comp_level 6;
  15. gzip_types text/plain text/css application/json application/javascript text/xml;
  16. # 缓冲区设置
  17. client_body_buffer_size 128k;
  18. client_header_buffer_size 16k;
  19. large_client_header_buffers 4 32k;
  20. # 包含子配置
  21. include /etc/nginx/conf.d/*.conf;
  22. }

四、负载均衡集群部署

4.1 四层负载均衡配置

使用stream模块实现TCP代理(如MySQL集群):

  1. stream {
  2. upstream mysql_backend {
  3. server 10.0.0.1:3306;
  4. server 10.0.0.2:3306;
  5. server 10.0.0.3:3306;
  6. }
  7. server {
  8. listen 3306;
  9. proxy_pass mysql_backend;
  10. proxy_timeout 3s;
  11. proxy_connect_timeout 1s;
  12. }
  13. }

4.2 七层负载均衡策略

HTTP应用的负载均衡配置示例:

  1. upstream web_backend {
  2. # 权重轮询(默认)
  3. server 10.0.0.4:80 weight=5;
  4. server 10.0.0.5:80 weight=3;
  5. # IP哈希(会话保持)
  6. # ip_hash;
  7. # 最少连接
  8. # least_conn;
  9. }
  10. server {
  11. listen 80;
  12. location / {
  13. proxy_pass http://web_backend;
  14. proxy_set_header Host $host;
  15. proxy_set_header X-Real-IP $remote_addr;
  16. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  17. proxy_connect_timeout 60s;
  18. proxy_read_timeout 60s;
  19. proxy_send_timeout 60s;
  20. }
  21. }

4.3 健康检查配置

通过max_failsfail_timeout实现故障自动隔离:

  1. upstream api_backend {
  2. server 10.0.0.6:8080 max_fails=3 fail_timeout=30s;
  3. server 10.0.0.7:8080 max_fails=3 fail_timeout=30s;
  4. }

五、监控与维护

5.1 状态监控接口

启用stub_status模块获取实时指标:

  1. server {
  2. listen 8080;
  3. server_name status.example.com;
  4. allow 10.0.0.0/8;
  5. deny all;
  6. location /nginx_status {
  7. stub_status on;
  8. access_log off;
  9. }
  10. }

访问http://status.example.com/nginx_status可获取:

  • 活动连接数
  • 每秒请求数
  • 读写状态分布

5.2 日志分析方案

推荐使用ELK或Loki+Grafana构建日志分析平台,基础日志轮转配置:

  1. # 创建日志轮转配置
  2. cat > /etc/logrotate.d/nginx <<EOF
  3. /var/www/*/logs/*.log {
  4. daily
  5. missingok
  6. rotate 14
  7. compress
  8. delaycompress
  9. notifempty
  10. create 0640 nginx adm
  11. sharedscripts
  12. postrotate
  13. if [ -f /usr/local/nginx/logs/nginx.pid ]; then
  14. kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
  15. fi
  16. endscript
  17. }
  18. EOF

六、常见问题排查

  1. 502 Bad Gateway:检查后端服务是否正常运行,代理超时设置是否合理
  2. 连接数过高:调整worker_connections(默认512)和worker_rlimit_nofile
  3. SSL握手失败:验证证书链完整性,检查协议版本支持
  4. 静态文件403:确认目录权限和SELinux上下文(chcon -Rt httpd_sys_content_t /var/www

通过本文提供的完整配置方案,运维人员可快速构建从单机服务到集群架构的Nginx应用体系。建议结合具体业务场景进行参数调优,并定期进行安全审计与性能基准测试。