插件窝 干货文章 Nginx的反向代理与安全性能优化

Nginx的反向代理与安全性能优化

Nginx 配置 server header 321    来源:    2025-04-20

Nginx反向代理与安全性能优化指南

一、反向代理基础配置

1. 基本反向代理配置

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

2. 负载均衡配置

upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com backup;

    # 负载均衡算法
    least_conn; # 最少连接
    # ip_hash; # IP哈希
    # hash $request_uri consistent; # 一致性哈希
}

server {
    location / {
        proxy_pass http://backend;
    }
}

二、安全优化配置

1. SSL/TLS 配置

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

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # 启用TLS 1.2/1.3,禁用不安全的协议
    ssl_protocols TLSv1.2 TLSv1.3;

    # 推荐加密套件
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';

    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # 启用OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
}

2. HTTP安全头部

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 Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

3. 防止常见攻击

# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

# 隐藏Nginx版本信息
server_tokens off;

# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";

# 防止MIME类型混淆攻击
add_header X-Content-Type-Options "nosniff";

# 禁用内容类型嗅探
add_header X-Content-Type-Options nosniff;

# 防止XSS攻击
add_header X-XSS-Protection "1; mode=block";

三、性能优化配置

1. 缓存优化

# 代理缓存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_key "$scheme$request_method$host$request_uri";
    }
}

2. 连接优化

# 全局配置
worker_processes auto; # 自动设置worker数量
worker_rlimit_nofile 100000; # 每个worker能打开的文件描述符数量

events {
    worker_connections 4096; # 每个worker的最大连接数
    multi_accept on; # 同时接受多个新连接
    use epoll; # 使用epoll事件模型(Linux)
}

http {
    # TCP优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接超时设置
    keepalive_timeout 30;
    keepalive_requests 1000;
    reset_timedout_connection on;
    client_body_timeout 10;
    send_timeout 2;

    # 缓冲区优化
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;
}

3. 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 application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
gzip_buffers 16 8k;
gzip_http_version 1.1;

四、高级安全配置

1. 限制访问

# 限制连接频率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
    location / {
        limit_req zone=one burst=20 nodelay;
    }
}

# 限制并发连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location / {
        limit_conn addr 10;
    }
}

# IP白名单
location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

2. 防止DDoS

# 限制单个IP的连接数
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 20;

# 限制请求速率
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=100r/m;

# 屏蔽恶意User-Agent
if ($http_user_agent ~* (wget|curl|libwww-perl|nikto|sqlmap|nmap) ) {
    return 403;
}

# 屏蔽常见扫描路径
location ~* (wp-admin|wp-login|.git|.env|.svn|.htaccess) {
    deny all;
    return 404;
}

3. Web应用防火墙(WAF)功能

# 防止SQL注入
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
    set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
    return 403;
}

# 防止XSS攻击
set $block_xss 0;
if ($query_string ~ "<script.*>") {
    set $block_xss 1;
}
if ($block_xss = 1) {
    return 403;
}

# 防止目录遍历
if ($request_uri ~* "\.\./") {
    return 403;
}

五、监控与日志

1. 访问日志优化

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';

access_log /var/log/nginx/access.log main buffer=32k flush=5m;
error_log /var/log/nginx/error.log warn;

2. 实时状态监控

# 启用Nginx状态页
server {
    listen 127.0.0.1:8080;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

六、最佳实践建议

  1. 定期更新Nginx:保持Nginx版本最新以获取安全补丁和性能改进

  2. 最小化模块:只编译安装必要的模块,减少攻击面

  3. 分离配置:将不同站点的配置分离到单独文件中,使用include指令引入

  4. 定期审计配置:使用nginx -t测试配置,定期审查安全设置

  5. 日志轮转:设置logrotate定期轮转日志文件

  6. 文件权限:确保Nginx运行用户对配置文件有最小必要权限

  7. 使用fail2ban:配合fail2ban防止暴力破解

  8. 启用ModSecurity:对于高安全需求,考虑集成ModSecurity WAF

通过以上配置和最佳实践,可以显著提升Nginx反向代理的安全性和性能,为后端服务提供可靠、高效的代理服务。