插件窝 干货文章 如何使用Nginx进行HTTP请求的日志记录和分析

如何使用Nginx进行HTTP请求的日志记录和分析

Nginx log access HTTP 632    来源:    2025-04-13

使用Nginx进行HTTP请求日志记录和分析指南

Nginx提供了强大的日志功能,可以帮助你记录和分析HTTP请求。以下是完整的配置和使用方法:

1. 配置Nginx访问日志

基本访问日志配置

在nginx.conf或站点配置文件中添加或修改access_log指令:

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

    access_log /var/log/nginx/access.log main;
}

常用日志变量

  • $remote_addr - 客户端IP地址
  • $remote_user - 认证用户名
  • $time_local - 本地时间
  • $request - 完整的请求行(GET/POST等)
  • $status - 响应状态码
  • $body_bytes_sent - 发送给客户端的字节数
  • $http_referer - 来源页面
  • $http_user_agent - 客户端浏览器信息
  • $http_x_forwarded_for - 代理服务器IP链(如果有)
  • $request_time - 请求处理时间(秒)
  • $upstream_response_time - 后端服务器响应时间

高级日志配置

log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '$request_time $upstream_response_time '
                    '$scheme $host $server_port';

access_log /var/log/nginx/access.log detailed buffer=32k flush=5m;

2. 日志分割和轮转

使用logrotate

创建/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
}

3. 日志分析工具

使用GoAccess实时分析

# 安装
sudo apt-get install goaccess  # Debian/Ubuntu
sudo yum install goaccess     # CentOS/RHEL

# 实时分析
goaccess /var/log/nginx/access.log -a

使用AWK进行简单分析

# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn

# 统计访问量最高的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20

# 统计访问量最高的URL
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head -20

使用ELK Stack (Elasticsearch, Logstash, Kibana)

  1. 安装ELK组件
  2. 配置Logstash处理Nginx日志:
input {
  file {
    path => "/var/log/nginx/access.log"
    start_position => "beginning"
  }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
  date {
    match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}

4. 性能优化提示

  1. 对于高流量网站,考虑使用缓冲日志:

    access_log /path/to/log.gz combined gzip=1 buffer=32k flush=5m;
    
  2. 只记录必要的字段以减少I/O压力

  3. 对于特定路径禁用日志:

    location /static/ {
     access_log off;
    }
    

5. 安全日志配置

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

access_log /var/log/nginx/security.log security;

通过以上配置和分析方法,你可以全面掌握Nginx的HTTP请求情况,进行性能监控、安全分析和流量统计。