参考资料

  1. 如何验证Nginx配置是否生效?
  2. nginx -g详细说明以及案例
  3. Nginx负载均衡策略详解
  4. Nginx配置详细说明以及案例
  5. 是否有自动化的安全检测nginx工具?
  6. nginx 配置反向代理
  7. NginxHTTPS服务器搭建详细说明以及案例
  8. Nginxtry_files 文件判断指令详细说明以及案例

监控Nginx访问日志的方法

  1. 日志文件位置

    • 默认路径:/var/log/nginx/access.log

    • 可通过Nginx配置文件(nginx.conf)中的access_log指令确认路径

  2. 实时监控命令

    tail -f /var/log/nginx/access.log
  3. 常用分析工具

    • 基础命令:

      # 统计总访问量
      wc -l /var/log/nginx/access.log
      
      # 查看独立IP数量
      awk '{print $1}' access.log | sort | uniq | wc -l
    • 高级工具:

      # 使用GoAccess(实时可视化工具)
      goaccess /var/log/nginx/access.log -a
  4. 日志轮转配置
    /etc/logrotate.d/nginx中配置自动轮转:

    /var/log/nginx/*.log {
        daily
        missingok
        rotate 14
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        postrotate
            invoke-rc.d nginx rotate >/dev/null 2>&1
        endscript
    }
  5. 监控脚本示例

    #!/bin/bash
    LOGFILE="/var/log/nginx/access.log"
    ALERT_LEVEL=1000  # 每分钟警报阈值
    
    while true
    do
        CURRENT=$(wc -l < $LOGFILE)
        sleep 60
        NEW=$(wc -l < $LOGFILE)
        DIFF=$((NEW - CURRENT))
        
        if [ $DIFF -gt $ALERT_LEVEL ]; then
            echo "High traffic detected: $DIFF requests/minute" | mail -s "NGINX Alert" admin@example.com
        fi
    done
  6. 日志格式示例
    典型组合格式:

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