Skip to content
0

文章发布较早,内容可能过时,阅读注意甄别。

前言

Nginx 作为高性能 Web 服务器和反向代理,是互联网应用的第一道防线。本文总结生产环境中的安全加固措施。

1. 基础安全配置

1.1 隐藏版本号

nginx
http {
    # 隐藏 Nginx 版本信息
    server_tokens off;

    # 自定义 Server 头(可选)
    more_set_headers "Server: WebServer";
}

验证

bash
curl -I https://example.com
# 不显示:Server: nginx/1.20.2
# 仅显示:Server: nginx

1.2 限制请求方法

nginx
server {
    listen 80;
    server_name example.com;

    # 只允许 GET、POST、HEAD
    if ($request_method !~ ^(GET|POST|HEAD)$) {
        return 405;
    }
}

1.3 禁止访问敏感文件

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

# 禁止访问备份文件
location ~* \.(bak|old|tmp|swp|sql|gz|tar)$ {
    deny all;
}

# 禁止访问配置文件
location ~* \.(conf|ini|json)$ {
    deny all;
}

2. HTTPS 配置

2.1 强制 HTTPS

nginx
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

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

    # SSL 证书配置
    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    # SSL 协议和加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;

    # HSTS(强制 HTTPS)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # SSL 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
}

2.2 SSL 安全优化

nginx
# OCSP Stapling(提升 SSL 握手性能)
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

# Diffie-Hellman 参数
ssl_dhparam /path/to/dhparam.pem;

生成 DH 参数

bash
openssl dhparam -out /etc/nginx/dhparam.pem 2048

3. 安全响应头

3.1 常用安全头

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

# X-Content-Type-Options:防止 MIME 类型嗅探
add_header X-Content-Type-Options "nosniff" always;

# X-XSS-Protection:启用 XSS 过滤
add_header X-XSS-Protection "1; mode=block" always;

# Referrer-Policy:控制 Referer 信息泄露
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# Content-Security-Policy:内容安全策略
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

# Permissions-Policy:权限策略
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

3.2 完整安全配置示例

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

    # SSL 配置
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    # 安全响应头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    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 "strict-origin-when-cross-origin" always;

    # 其他配置...
}

4. 防 DDoS 攻击

4.1 限制连接数

nginx
http {
    # 定义连接限制区域
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    server {
        # 限制每个 IP 最多 10 个并发连接
        limit_conn conn_limit 10;
    }
}

4.2 限制请求速率

nginx
http {
    # 定义请求速率限制区域
    # 每个 IP 每秒最多 10 个请求,突发 20 个
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

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

4.3 综合防护配置

nginx
http {
    # 连接限制
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    # 请求速率限制
    limit_req_zone $binary_remote_addr zone=general_limit:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;

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

        # 全局连接限制
        limit_conn conn_limit 10;

        # 普通页面限制
        location / {
            limit_req zone=general_limit burst=20 nodelay;
        }

        # API 接口严格限制
        location /api/ {
            limit_req zone=api_limit burst=5 nodelay;
        }
    }
}

5. IP 访问控制

5.1 白名单/黑名单

nginx
# 允许特定 IP 访问管理后台
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.100;
    deny all;
}

# 禁止特定 IP 访问
location / {
    deny 203.0.113.0/24;
    allow all;
}

5.2 使用 GeoIP 模块

nginx
http {
    # 加载 GeoIP 模块
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    # 定义允许的国家
    map $geoip_country_code $allowed_country {
        default no;
        CN yes;
        US yes;
    }

    server {
        if ($allowed_country = no) {
            return 403;
        }
    }
}

6. 防 SQL 注入和 XSS

nginx
# 检测 SQL 注入特征
if ($query_string ~* "(union|select|insert|drop|delete|update|exec|script|javascript)") {
    return 403;
}

# 检测路径穿越攻击
if ($request_uri ~* "(\.\./|\.\.\\)") {
    return 403;
}

# 检测文件上传漏洞
if ($request_uri ~* "(\.php|\.asp|\.jsp)") {
    return 403;
}

7. 日志记录与审计

7.1 访问日志

nginx
http {
    # 自定义日志格式
    log_format security '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent" '
                        '"$http_x_forwarded_for" "$request_time"';

    server {
        # 记录访问日志
        access_log /var/log/nginx/access.log security;

        # 记录被拒绝的请求
        access_log /var/log/nginx/denied.log security if=$limit_req_rejected;
    }
}

7.2 错误日志

nginx
# 全局错误日志
error_log /var/log/nginx/error.log warn;

server {
    # 服务器级别错误日志
    error_log /var/log/nginx/example.com.error.log;
}

8. 防止爬虫和恶意扫描

8.1 User-Agent 过滤

nginx
# 定义恶意 User-Agent
map $http_user_agent $blocked_agent {
    default 0;
    ~*malicious 1;
    ~*sqlmap 1;
    ~*nikto 1;
    ~*masscan 1;
}

server {
    if ($blocked_agent) {
        return 403;
    }
}

8.2 限制爬虫访问频率

nginx
# 为爬虫单独设置限制
map $http_user_agent $is_bot {
    default 0;
    ~*googlebot 1;
    ~*bingbot 1;
    ~*baiduspider 1;
}

limit_req_zone $binary_remote_addr zone=bot_limit:10m rate=1r/s;

server {
    location / {
        if ($is_bot) {
            limit_req zone=bot_limit burst=5;
        }
    }
}

9. Buffer 溢出防护

nginx
http {
    # 限制请求体大小
    client_body_buffer_size 1K;
    client_header_buffer_size 1k;
    client_max_body_size 20M;
    large_client_header_buffers 2 1k;

    # 请求超时设置
    client_body_timeout 10;
    client_header_timeout 10;
    keepalive_timeout 5 5;
    send_timeout 10;
}

10. 完整安全配置示例

nginx
http {
    # 基础安全
    server_tokens off;

    # 连接和请求限制
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

    # Buffer 限制
    client_body_buffer_size 1K;
    client_max_body_size 20M;

    # 日志格式
    log_format security '$remote_addr - [$time_local] "$request" '
                        '$status "$http_user_agent"';

    server {
        listen 80;
        server_name example.com;
        return 301 https://$server_name$request_uri;
    }

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

        # SSL 配置
        ssl_certificate /etc/nginx/ssl/cert.pem;
        ssl_certificate_key /etc/nginx/ssl/key.pem;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;

        # 安全响应头
        add_header Strict-Transport-Security "max-age=31536000" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;

        # 连接和请求限制
        limit_conn conn_limit 10;
        limit_req zone=req_limit burst=20 nodelay;

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

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

        # 日志
        access_log /var/log/nginx/access.log security;
        error_log /var/log/nginx/error.log;

        location / {
            root /var/www/html;
            index index.html;
        }
    }
}

11. 安全检查清单

  • 隐藏 Nginx 版本号
  • 配置 HTTPS 并强制使用
  • 添加安全响应头
  • 配置连接和请求速率限制
  • 禁止访问敏感文件
  • 限制允许的 HTTP 方法
  • 配置 IP 白名单/黑名单
  • 启用详细日志记录
  • 定期更新 Nginx 版本
  • 使用 WAF(如 ModSecurity)

12. 常用安全检测工具

bash
# SSL 配置检测
curl https://www.ssllabs.com/ssltest/analyze.html?d=example.com

# 安全响应头检测
curl -I https://example.com | grep -E "(X-Frame|X-Content|X-XSS|Strict-Transport)"

# Nginx 配置测试
nginx -t

# 安全扫描
nikto -h https://example.com

参考资料

最近更新