Nginx反向代理与负载均衡配置详解

· 阅读约需33分钟

前言

Nginx作为高性能的Web服务器和反向代理软件,在现代Web架构中扮演着至关重要的角色。本文将深入讲解Nginx的反向代理、负载均衡、静态资源服务、HTTPS配置等核心功能,帮助你构建高性能、高可用的Web服务架构。

本文基于Nginx 1.20+版本,适用于CentOS 7/8、Ubuntu 18.04/20.04等主流发行版。


一、Nginx基础与安装

1.1 Nginx核心特性

  • 高并发连接:单台服务器支持数万并发连接
  • 低内存消耗:10000个连接仅消耗约2.5MB内存
  • 高可靠性:Master-Worker多进程架构
  • 热部署:平滑升级、配置重载不中断服务
  • 反向代理:支持HTTP、HTTPS、WebSocket、gRPC等
  • 负载均衡:轮询、加权轮询、IP哈希、最少连接等算法
  • 静态资源服务:高效处理静态文件,支持sendfile
  • 缓存支持:多层缓存机制,减轻后端压力

1.2 Yum安装(CentOS)

# 安装EPEL源
yum install -y epel-release

# 安装Nginx
yum install -y nginx

# 启动并设置开机自启
systemctl start nginx
systemctl enable nginx

# 验证安装
nginx -v
nginx -t

1.3 源码编译安装

# 安装依赖
yum install -y gcc gcc-c++ make zlib-devel pcre-devel openssl-devel

# 下载源码
cd /usr/local/src
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar zxf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 编译配置
./configure \
  --prefix=/usr/local/nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_gzip_static_module \
  --with-http_stub_status_module \
  --with-stream

# 编译安装
make && make install

# 创建软链接
ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx

1.4 Nginx目录结构

/usr/local/nginx/
├── conf/              # 配置文件目录
│   ├── nginx.conf     # 主配置文件
│   └── conf.d/        # 子配置目录
├── html/              # 默认网站根目录
├── logs/              # 日志目录
│   ├── access.log     # 访问日志
│   └── error.log      # 错误日志
└── sbin/
    └── nginx          # 主程序

二、Nginx核心配置详解

2.1 主配置文件结构

# 全局配置
user  nginx;
worker_processes  auto;  # 自动设置为CPU核心数
worker_rlimit_nofile 65535;

# 事件模块
events {
    use epoll;
    worker_connections  65535;
    multi_accept on;
}

# HTTP模块
http {
    include       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"';

    # 基础优化
    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;

    # Gzip压缩
    gzip  on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss;

    # 包含子配置文件
    include /usr/local/nginx/conf/conf.d/*.conf;
}

2.2 性能优化配置

# 内核参数优化(/etc/sysctl.conf)
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 1024 65535
net.core.netdev_max_backlog = 32768

# 生效配置
sysctl -p

三、反向代理配置实战

3.1 基础反向代理

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;

        # 代理头信息
        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_set_header X-Forwarded-Proto $scheme;

        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        # 缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}

3.2 常用代理参数详解

参数作用推荐值
proxy_set_header设置转发给后端的请求头必配
proxy_connect_timeout连接后端超时30s
proxy_read_timeout读取后端响应超时60s
proxy_send_timeout发送请求到后端超时60s
proxy_buffering是否缓冲后端响应on
proxy_cache启用缓存按需

3.3 WebSocket代理配置

location /ws {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 86400;  # 长连接超时
}

3.4 路径重写与转发

server {
    listen 80;
    server_name example.com;

    # 路径重写:/api/* -> /*
    location /api/ {
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://backend;
    }

    # 永久重定向
    location /old {
        return 301 https://example.com/new;
    }

    # 临时重定向
    location /temp {
        return 302 https://example.com/temp-page;
    }
}

四、负载均衡配置

4.1 负载均衡算法

1. 轮询(默认)

upstream backend {
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

2. 加权轮询

upstream backend {
    server 192.168.1.10:8080 weight=3;  # 3/6流量
    server 192.168.1.11:8080 weight=2;  # 2/6流量
    server 192.168.1.12:8080 weight=1;  # 1/6流量
}

3. IP哈希(会话保持)

upstream backend {
    ip_hash;  # 同一IP始终转发到同一后端
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
}

4. 最少连接

upstream backend {
    least_conn;  # 转发到活跃连接最少的后端
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
}

4.2 健康检查与故障转移

upstream backend {
    server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 backup;  # 备用服务器
}

# max_fails=3:连续失败3次标记为不可用
# fail_timeout=30s:30秒后重新尝试
# backup:仅当其他服务器都不可用时启用

4.3 完整负载均衡示例

upstream web_cluster {
    least_conn;
    server 192.168.1.10:8080 weight=2 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:8080 backup;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://web_cluster;
        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_set_header Connection "";
    }
}

五、静态资源服务优化

5.1 静态文件服务配置

server {
    listen 80;
    server_name static.example.com;
    root /data/static;
    index index.html;

    # 浏览器缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # 开启sendfile零拷贝
    sendfile on;
    tcp_nopush on;

    # 开启目录列表(按需)
    # autoindex on;
    # autoindex_exact_size off;
    # autoindex_localtime on;
}

5.2 图片防盗链

location ~* \.(jpg|jpeg|png|gif|swf)$ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
        # 或返回防盗链图片
        # rewrite ^/ https://example.com/forbidden.jpg;
    }
}

5.3 跨域配置

location / {
    # 允许跨域
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

    # 预检请求处理
    if ($request_method = 'OPTIONS') {
        add_header Access-Control-Max-Age 1728000;
        add_header Content-Type 'text/plain; charset=utf-8';
        add_header Content-Length 0;
        return 204;
    }
}

六、HTTPS与HTTP/2配置

6.1 SSL证书配置

server {
    listen 443 ssl http2;
    server_name example.com;

    # 证书路径
    ssl_certificate /etc/ssl/certs/example.com.pem;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # SSL优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://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_set_header X-Forwarded-Proto https;
    }
}

# HTTP强制跳转HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

6.2 Let’s Encrypt免费证书

# 安装certbot
yum install -y certbot python3-certbot-nginx

# 自动获取并配置证书
certbot --nginx -d example.com -d www.example.com

# 自动续期(添加到crontab)
0 3 * * * certbot renew --quiet --deploy-hook "systemctl reload nginx"

七、缓存配置

7.1 代理缓存配置

# http块中配置缓存路径
http {
    proxy_cache_path /var/cache/nginx 
        levels=1:2 
        keys_zone=my_cache:10m 
        max_size=10g 
        inactive=7d 
        use_temp_path=off;

    server {
        location / {
            proxy_pass http://backend;
            proxy_cache my_cache;
            proxy_cache_key $host$uri$is_args$args;
            proxy_cache_valid 200 304 12h;
            proxy_cache_valid 301 1d;
            proxy_cache_valid any 1m;

            # 添加缓存状态头
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

7.2 缓存清理

# 清理特定URL缓存
rm -rf /var/cache/nginx/$(echo -n "example.com/path" | md5sum | cut -c1-32)

# 清理全部缓存
rm -rf /var/cache/nginx/*

八、安全加固配置

8.1 基础安全配置

# 隐藏Nginx版本号
server_tokens off;

# 限制请求大小
client_max_body_size 10m;

# 防DDOS:限制连接数
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_conn conn_limit 100;

# 防DDOS:限制请求速率
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_req zone=req_limit burst=20 nodelay;

# 禁止访问敏感文件
location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}

location ~* \.(sql|bak|conf|ini|log)$ {
    deny all;
}

8.2 Basic Auth认证

# 安装httpd-tools
yum install -y httpd-tools

# 创建密码文件
htpasswd -c /etc/nginx/.htpasswd admin
location /admin {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_pass http://backend;
}

九、Nginx常用命令

# 启动
nginx

# 停止
nginx -s stop    # 立即停止
nginx -s quit    # 优雅停止

# 重载配置(平滑重启)
nginx -s reload

# 重新打开日志文件(日志切割用)
nginx -s reopen

# 测试配置文件
nginx -t
nginx -T  # 测试并显示完整配置

# 查看版本
nginx -v
nginx -V  # 查看编译参数

十、常见问题排查

10.1 502 Bad Gateway

  • 检查后端服务是否正常运行
  • 检查防火墙/SELinux
  • 检查proxy_pass地址是否正确
  • 查看error.log详细错误信息

10.2 403 Forbidden

  • 检查文件/目录权限(Nginx用户需要读权限)
  • 检查root/alias配置是否正确
  • 检查SELinux是否阻止访问

10.3 413 Request Entity Too Large

# 调大请求体限制
client_max_body_size 100m;

10.4 查看实时连接状态

# 启用状态页面
location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

总结

Nginx作为Web服务器和反向代理的核心组件,掌握其配置和优化是运维工程师的必备技能。本文涵盖了:

  1. Nginx安装:Yum安装和源码编译两种方式
  2. 核心配置:性能优化、事件模型、基础参数
  3. 反向代理:HTTP、WebSocket代理,路径重写
  4. 负载均衡:多种算法、健康检查、故障转移
  5. 静态资源:缓存、防盗链、跨域配置
  6. HTTPS配置:SSL证书、HTTP/2、安全优化
  7. 缓存机制:代理缓存配置与清理
  8. 安全加固:防DDOS、访问控制、Basic Auth

熟练掌握这些配置,你将能够构建出高性能、高可用、高安全的Web服务架构。


参考资料: