插件窝 干货文章 Nginx日志分析与安全检测

Nginx日志分析与安全检测

log access Nginx bash 323    来源:    2025-04-20

Nginx日志分析与安全检测指南

一、Nginx日志基础

日志文件位置

  • 默认访问日志路径:/var/log/nginx/access.log
  • 默认错误日志路径:/var/log/nginx/error.log
  • 可通过nginx.conf中的配置查看具体路径: http { access_log /path/to/access.log; error_log /path/to/error.log; }

日志格式配置

Nginx默认使用combined格式,也可自定义:

log_format security '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" '
                   '$request_time $upstream_response_time';

二、日志分析工具

1. 命令行工具

  • grep:基础过滤

    grep "404" access.log
    grep -E "POST|PUT|DELETE" access.log
    
  • awk:高级处理

    awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
    
  • cut:字段提取

    cut -d' ' -f1 access.log | sort | uniq -c | sort -nr
    

2. 专用日志分析工具

  • GoAccess:实时可视化分析

    goaccess access.log -o report.html --log-format=COMBINED
    
  • AWStats:详细统计分析

  • ELK Stack:大规模日志分析平台

三、安全检测要点

1. 常见攻击模式检测

  • SQL注入

    grep -Ei "(select|union|insert|delete|update|drop|alter|truncate).*(from|into|where)" access.log
    
  • XSS攻击

    grep -Ei "(<script|javascript:|onerror=|onload=)" access.log
    
  • 目录遍历

    grep -Ei "(\.\./|\.\.\\|%2e%2e|%252e)" access.log
    
  • 暴力破解

    awk '{print $1,$7}' access.log | grep "wp-login.php" | awk '{print $1}' | sort | uniq -c | sort -nr
    

2. 异常访问检测

  • 高频访问IP

    awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
    
  • 非200状态码

    awk '$9 != 200 {print $0}' access.log
    
  • 大文件下载

    awk '$10 > 10000000 {print $7,$10,$1}' access.log | sort -nr
    

四、自动化监控方案

1. Fail2Ban配置

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
action = iptables[name=HTTP, port=http, protocol=tcp]
logpath = /var/log/nginx/error.log
maxretry = 3

2. 自定义监控脚本示例

#!/bin/bash

# 监控5分钟内404错误
ERROR_COUNT=$(awk -v d1="$(date --date="-5 min" "+%d/%b/%Y:%H:%M")" -v d2="$(date "+%d/%b/%Y:%H:%M")" '$0 > d1 && $0 < d2 && $9 == 404' access.log | wc -l)

if [ $ERROR_COUNT -gt 100 ]; then
    echo "High 404 errors detected: $ERROR_COUNT" | mail -s "Nginx Alert" admin@example.com
fi

五、日志轮转配置

编辑/etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

六、高级安全建议

  1. 启用GeoIP过滤:屏蔽特定国家IP
  2. 设置速率限制limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
  3. 禁用危险HTTP方法if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }
  4. 隐藏Nginx版本信息server_tokens off;

通过系统化的日志分析和安全检测,可以显著提升Nginx服务器的安全性,及时发现并应对潜在威胁。