Nginx 最小安全配置模板

以下是 Nginx 最小安全配置模板,涵盖基础加固、访问控制、传输加密、安全响应头等常见安全项,可直接作为生产环境的起点。

1.完整配置模板

bash 复制代码
# ================= 全局配置 =================
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /usr/local/nginx/logs/nginx.pid;

events {
    worker_connections  65535;
    use                   epoll;
    multi_accept          on;
}

http {
    # ============ 基础安全 ============
    # 隐藏版本号(防止泄露版本信息被针对性攻击)
    server_tokens off;

    # 禁用目录列表(防止目录遍历泄露文件结构)
    autoindex off;

    # 禁用 SSI(防止服务端包含执行)
    ssi off;

    # 重定向时不暴露端口号
    port_in_redirect off;

    # 隐藏后端技术标识(反向代理场景)
    proxy_hide_header X-Powered-By;
    proxy_hide_header Server;

    # ============ 日志格式 ============
    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;

    # ============ 请求限制 ============
    # 单IP请求频率限制:10r/s,突发20,不延迟
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

    # 单IP并发连接数限制:最多20个
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    # ============ 文件上传限制 ============
    # 最大请求体大小(防止大文件上传耗尽资源)
    client_max_body_size 10m;

    # 请求体缓冲区大小
    client_body_buffer_size 128k;

    # ============ 缓冲区溢出防护 ============
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    # ============ 超时设置(防慢速攻击) ============
    client_header_timeout 10s;
    client_body_timeout   10s;
    send_timeout          10s;
    keepalive_timeout     65s;

    # ============ MIME类型安全 ============
    include       mime.types;
    default_type  application/octet-stream;

    # ============ 默认Server(拦截非法Host头) ============
    server {
        listen      80 default_server;
        server_name _;
        return      403;
    }

    # ============ 业务Server ============
    server {
        listen      80;
        server_name example.com www.example.com;

        # 强制跳转HTTPS
        return 301 https://$host$request_uri;
    }

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

        # ============ SSL/TLS安全配置 ============
        ssl_certificate     /etc/nginx/ssl/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/privkey.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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
        ssl_prefer_server_ciphers on;

        # 会话复用
        ssl_session_timeout 1d;
        ssl_session_cache   shared:MozSSL:10m;

        # OCSP装订(提升SSL握手效率)
        ssl_stapling        on;
        ssl_stapling_verify on;

        # HSTS(强制浏览器使用HTTPS,一年)
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        # ============ 安全响应头 ============
        # 防点击劫持
        add_header X-Frame-Options "SAMEORIGIN" always;

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

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

        # 控制Referer信息传递
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;

        # 内容安全策略(根据实际业务调整)
        add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self'; frame-ancestors 'self';" always;

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

        # ============ 应用请求限制 ============
        limit_req   zone=req_limit burst=20 nodelay;
        limit_conn  conn_limit 20;

        # ============ 站点根目录 ============
        root   /var/www/html;
        index  index.html index.htm;

        location / {
            try_files $uri $uri/ =404;
        }

        # ============ 敏感路径保护 ============
        # 管理后台:IP白名单 + 基础认证
        location /admin {
            allow 192.168.1.0/24;
            allow 10.0.0.0/8;
            deny all;
            auth_basic "Admin Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }

        # 禁止访问敏感文件
        location ~* \.(conf|log|bak|sql|git|htaccess|htpasswd)$ {
            deny all;
        }

        # 禁止在上传目录执行脚本
        location ~* /uploads/.*\.(php|php5|pl|py|jsp|asp)$ {
            deny all;
        }

        # ============ 自定义错误页面 ============
        error_page 403 /403.html;
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;

        location = /403.html {
            root /var/www/html;
            internal;
        }
        location = /404.html {
            root /var/www/html;
            internal;
        }
        location = /50x.html {
            root /var/www/html;
            internal;
        }
    }
}

2.各模块作用速查

模块 关键配置 防护目标
基础安全 server_tokens offautoindex off 隐藏版本信息、防止目录遍历
请求限制 limit_req_zonelimit_conn_zone 防CC攻击、防暴力破解
文件上传 client_max_body_size 10m 防止大文件耗尽磁盘/内存
超时设置 client_body_timeout 10s 防御慢速HTTP攻击(Slowloris)
SSL/TLS ssl_protocols TLSv1.2 TLSv1.3 禁用弱协议,启用前向保密
安全响应头 X-Frame-OptionsCSP 防点击劫持、XSS、MIME嗅探
HTTP方法限制 if ($request_method !~ ...) 禁用危险方法(TRACE、CONNECT等)
敏感路径保护 location /admin + allow/deny IP白名单 + 基础认证双重防护
敏感文件拦截 `location ~* .(conf log

3.部署后验证清单

bash 复制代码
# 1. 测试配置语法
/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf

# 2. 重载生效
systemctl reload nginx

# 3. 检查响应头是否包含安全头
curl -I https://example.com | grep -E "X-Frame|X-Content|X-XSS|Strict-Transport"

# 4. 验证版本号已隐藏
curl -I https://example.com | grep Server

# 5. SSL评级检测(浏览器访问 https://www.ssllabs.com/ssltest/)
相关推荐
浅止菌1 小时前
嵌入式项目Makefile越写越乱?一张万能模板+5个技巧,告别重复劳动
linux
BerryS3N1 小时前
Cursor+GitOps:AI驱动的自动化运维新范式
运维·人工智能·自动化
IT小白杨1 小时前
多账号环境稳定性由什么决定:指纹、网络、存储如何共同决定账号安全
网络·安全·开源软件·业界资讯·指纹浏览器
明哥聊AI1 小时前
大模型安全攻防实战:从越狱到Prompt注入的攻防全解析(2026最新)
安全·prompt
网安蟹佬霸1 小时前
我国网络安全人才缺口现状、成因与对策研究
安全·web安全
FREEDOM_X2 小时前
嵌入式Linux摄像头采集与图像处理
linux·图像处理·ubuntu
studytosky3 小时前
OpenClaw 入门与 Skill 开发
linux·服务器·ai编程
kaoa0003 小时前
Linux入门攻坚——82、kvm虚拟化-2
linux·运维·服务器
OsDepK3 小时前
Windows快速部署Docker
运维·docker·容器
2601_954706493 小时前
云虚拟化终端架构解析:ARM 云端集群部署与自动化运维实践
运维·arm开发·架构