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

一、Nginx环境搭建与基础配置

1.1 系统环境准备

在Linux系统上部署Nginx前,需完成基础依赖安装。推荐使用Ubuntu/Debian系列系统,执行以下命令更新软件包索引并安装编译工具链:

  1. sudo apt update && sudo apt upgrade -y
  2. sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

其中libpcre3-dev提供正则表达式支持,zlib1g-dev用于GZIP压缩,libssl-dev是HTTPS模块必需的依赖。对于CentOS/RHEL系统,需替换为yum groupinstall "Development Tools"并单独安装对应开发包。

1.2 源码编译安装

采用源码编译方式可灵活控制功能模块,具体步骤如下:

  1. 创建专用用户:遵循最小权限原则,创建无登录权限的nginx用户

    1. sudo groupadd -r nginx
    2. sudo useradd -r -g nginx -s /sbin/nologin nginx
  2. 下载解压源码:从官方托管仓库获取稳定版本(示例使用1.24.0版本)

    1. cd /tmp
    2. wget http://nginx.org/download/nginx-1.24.0.tar.gz
    3. tar zxvf nginx-*.tar.gz
    4. cd nginx-1.24.0
  3. 配置编译参数:关键参数说明如下:

    1. ./configure \
    2. --prefix=/usr/local/nginx \ # 安装目录
    3. --user=nginx \ # 运行用户
    4. --group=nginx \ # 运行组
    5. --with-http_ssl_module \ # 启用HTTPS
    6. --with-http_v2_module \ # 支持HTTP/2
    7. --with-http_realip_module \ # 获取真实客户端IP
    8. --with-http_stub_status_module \ # 监控状态页
    9. --with-stream \ # TCP/UDP代理支持
    10. --with-threads # 启用线程池
  4. 编译安装:使用多核编译加速过程

    1. make -j$(nproc) && sudo make install
  5. 注册系统服务:创建systemd服务文件实现开机自启
    ```ini

    /etc/systemd/system/nginx.service

    [Unit]
    Description=High performance web server
    After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

  1. 执行以下命令启用服务:
  2. ```bash
  3. sudo systemctl daemon-reload
  4. sudo systemctl enable --now nginx

二、静态资源服务配置

2.1 网站目录规划

遵循安全规范创建目录结构:

  1. sudo mkdir -p /var/www/static-site/{html,logs,conf}
  2. sudo chown -R nginx:nginx /var/www/static-site
  3. sudo chmod -R 750 /var/www/static-site

其中conf目录可用于存放站点专属配置,实现配置与代码分离。

2.2 基础配置示例

创建站点配置文件/var/www/static-site/conf/default.conf

  1. server {
  2. listen 80;
  3. server_name 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 main;
  7. error_log /var/www/static-site/logs/error.log warn;
  8. location / {
  9. try_files $uri $uri/ =404;
  10. expires 7d; # 静态资源缓存
  11. add_header Cache-Control "public";
  12. }
  13. # 禁止访问隐藏文件
  14. location ~ /\. {
  15. deny all;
  16. access_log off;
  17. log_not_found off;
  18. }
  19. }

在主配置文件nginx.conf的http块中引入:

  1. http {
  2. include /var/www/static-site/conf/*.conf;
  3. # 其他全局配置...
  4. }

2.3 性能优化技巧

  1. GZIP压缩:在http块添加

    1. gzip on;
    2. gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    3. gzip_min_length 1k;
    4. gzip_comp_level 6;
  2. 静态资源缓存:针对不同文件类型设置差异化缓存策略
    ```nginx
    location ~* .(jpg|jpeg|png|gif|ico)$ {
    expires 30d;
    access_log off;
    }

location ~* .(css|js)$ {
expires 7d;
add_header Cache-Control “public, no-transform”;
}

  1. # 三、负载均衡集群部署
  2. ## 3.1 反向代理基础
  3. 配置上游服务器组:
  4. ```nginx
  5. upstream backend_servers {
  6. server 192.168.1.100:8080 weight=5;
  7. server 192.168.1.101:8080;
  8. server 192.168.1.102:8080 backup;
  9. keepalive 32; # 保持长连接数量
  10. }

参数说明:

  • weight:权重分配,默认1
  • backup:备用服务器,主服务器不可用时启用
  • keepalive:减少TCP连接建立开销

3.2 负载均衡策略

  1. 轮询(默认):请求按顺序分配到各服务器
  2. IP哈希:相同客户端IP固定分配到同一服务器

    1. upstream backend_servers {
    2. ip_hash;
    3. server 192.168.1.100;
    4. server 192.168.1.101;
    5. }
  3. 最少连接:优先分配给活跃连接最少的服务器

    1. upstream backend_servers {
    2. least_conn;
    3. server 192.168.1.100;
    4. server 192.168.1.101;
    5. }

3.3 健康检查机制

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

  1. upstream backend_servers {
  2. server 192.168.1.100 max_fails=3 fail_timeout=30s;
  3. server 192.168.1.101 max_fails=3 fail_timeout=30s;
  4. }

当服务器连续3次失败(默认502/504状态码),将在30秒内不再分配新请求。

四、生产环境最佳实践

4.1 安全加固

  1. 隐藏版本信息:在nginx.conf中添加

    1. server_tokens off;
  2. 限制访问速率:防止CC攻击

    1. limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    2. server {
    3. location / {
    4. limit_req zone=one burst=5;
    5. }
    6. }

4.2 监控运维

  1. 状态监控页:启用stub_status模块

    1. location /nginx_status {
    2. stub_status on;
    3. allow 192.168.1.0/24;
    4. deny all;
    5. }
  2. 日志切割:创建日志切割脚本/etc/logrotate.d/nginx

    1. /usr/local/nginx/logs/*.log {
    2. daily
    3. missingok
    4. rotate 14
    5. compress
    6. delaycompress
    7. notifempty
    8. create 0640 nginx adm
    9. sharedscripts
    10. postrotate
    11. if [ -f /usr/local/nginx/logs/nginx.pid ]; then
    12. kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
    13. fi
    14. endscript
    15. }

4.3 高可用方案

采用Keepalived实现VIP漂移:

  1. 安装Keepalived

    1. sudo apt install keepalived
  2. 配置检测脚本/etc/keepalived/check_nginx.sh

    1. #!/bin/bash
    2. if [ ! -s /usr/local/nginx/logs/nginx.pid ]; then
    3. systemctl start nginx
    4. sleep 3
    5. if [ ! -s /usr/local/nginx/logs/nginx.pid ]; then
    6. exit 1
    7. fi
    8. fi
    9. exit 0
  3. 主节点配置示例
    ```ini
    vrrp_script chk_nginx {
    script “/etc/keepalived/check_nginx.sh”
    interval 2
    weight -20
    }

vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200/24
}
track_script {
chk_nginx
}
}
```

通过以上配置,开发者可构建从基础网站服务到企业级高可用架构的完整Nginx解决方案。实际部署时需根据业务规模调整线程池大小、连接数等参数,建议通过压力测试工具验证配置有效性。