当前位置:首页 > 未命名 > 正文内容

Nginx反向代理与负载均衡完全指南

廖万里10小时前未命名1

Nginx概述

Nginx是高性能的HTTP和反向代理服务器,以高并发、低内存占用著称。它既可以作为Web服务器,也可以作为负载均衡器和缓存服务器。

Nginx vs Apache

特性NginxApache
架构事件驱动进程/线程
并发高(万级连接)中等
内存较高
静态文件极快
动态内容需反向代理内置模块

基础配置

全局配置

# /etc/nginx/nginx.conf

user www-data;
worker_processes auto;  # 自动匹配CPU核心数
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 10240;  # 每个worker的最大连接数
    use epoll;  # Linux高性能事件模型
    multi_accept on;  # 同时接受多个连接
}

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;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript;
    
    # 包含站点配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

虚拟主机

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html index.php;
    
    # 访问日志
    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;
    
    # 静态文件
    location / {
        try_files $uri $uri/ =404;
    }
    
    # PHP处理
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    # 缓存静态资源
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

反向代理

upstream backend {
    server 127.0.0.1:3000;
    keepalive 32;  # 保持连接数
}

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        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 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
    
    # WebSocket支持
    location /ws {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

负载均衡

负载均衡策略

# 轮询(默认)
upstream backend {
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

# 加权轮询
upstream backend {
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1;
}

# IP Hash(会话保持)
upstream backend {
    ip_hash;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
}

# 最少连接
upstream backend {
    least_conn;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
}

# 健康检查
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;  # 备用服务器
}

SSL/TLS配置

server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL证书
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # SSL优化
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    
    # 现代加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=31536000" always;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
}

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

缓存配置

# 缓存区域定义
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m 
                 max_size=1g inactive=60m use_temp_path=off;

server {
    location /api/ {
        proxy_pass http://backend;
        
        # 启用缓存
        proxy_cache api_cache;
        proxy_cache_valid 200 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500;
        
        # 缓存键
        proxy_cache_key "$scheme$request_method$host$request_uri";
        
        # 添加缓存状态头
        add_header X-Cache-Status $upstream_cache_status;
        
        # 绕过缓存
        proxy_cache_bypass $http_x_nocache $cookie_nocache;
    }
}

安全加固

server {
    # 隐藏版本号
    server_tokens off;
    
    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Content-Security-Policy "default-src 'self'" always;
    
    # 限制请求体大小
    client_max_body_size 10m;
    
    # 限制连接数
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    limit_conn conn_limit 10;
    
    # 限制请求速率
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
    limit_req zone=req_limit burst=20 nodelay;
    
    # 防止目录遍历
    location ~* \.(?:git|svn|htaccess) {
        deny all;
    }
}

最佳实践

  1. 开启gzip压缩:减少传输大小
  2. 使用HTTP/2:多路复用提高性能
  3. 配置缓存:减轻后端压力
  4. 启用SSL:保证传输安全
  5. 监控日志:及时发现异常

Nginx是现代Web架构的核心组件,掌握其配置对构建高性能系统至关重要。

Nginx Server 1 Server 2 Server 3 Nginx负载均衡架构

本文链接:https://www.kkkliao.cn/?id=753 转载需授权!

分享到:

版权声明:本文由廖万里的博客发布,如需转载请注明出处。


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。