参考资料

  1. nginx代理详细讲解
  2. nginx 配置静态文件路径
  3. nginx 配置代理
  4. 如何查看nginx主配置文件路径方式
  5. Nginx stream模块详细说明以及案例
  6. Nginxreferer:请求头控制模块详细说明以及案例
  7. nginx 配置https
  8. Nginxallow、deny:IP访问控制模块详细说明以及案例
  1. 隐藏Nginx版本信息

  • 修改nginx.conf,在http块中添加:

server_tokens off;
  1. 限制HTTP请求方法

  • 只允许GET、POST、HEAD方法:

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}
  1. 禁用目录浏览

  • 在server块中添加:

autoindex off;
  1. 设置安全头部

  • 添加HTTP安全头部:

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
  1. 限制客户端请求体大小

  • 防止大文件上传攻击:

client_max_body_size 1m;
  1. 禁用不必要的HTTP方法

  • 在特定location禁用TRACE和DELETE:

location / {
    limit_except GET POST HEAD {
        deny all;
    }
}
  1. 配置SSL/TLS安全

  • 推荐配置:

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
  1. 限制访问频率

  • 防止暴力攻击:

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

location /login {
    limit_req zone=one burst=20;
}
  1. 禁止访问敏感文件

  • 限制访问点文件:

location ~ /\.(?!well-known).* {
    deny all;
    access_log off;
    log_not_found off;
}
  1. 日志记录完整客户端IP

  • 当使用代理时:

set_real_ip_from 192.168.1.0/24;
real_ip_header X-Forwarded-For;
log_format main '$remote_addr - $remote_user [$time_local] "$request"';
  1. 示例完整配置片段:

server {
    listen 443 ssl;
    server_tokens off;
    autoindex off;
    
    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=63072000" always;
    
    location / {
        limit_except GET POST {
            deny all;
        }
        client_max_body_size 1m;
    }
    
    location ~* \.(env|conf|bak)$ {
        deny all;
    }
}