关键是对静态资源请求分离日志输出:1. 用location正则匹配后缀并指定独立access_log;2. 自定义轻量log_format精简字段;3. 用location=排除robots.txt等干扰请求;4. 配置logrotate按日轮转保留30天。

要对 Nginx 中静态资源(如 .js、.css、.png、.jpg、.woff2 等)的访问进行独立统计,关键不是“过滤日志”,而是**按需分离日志输出**——即让静态资源请求写入单独的日志文件,便于后续用 awk、goaccess 或 ELK 等工具做精准分析。
1. 用 location 匹配静态资源路径并指定独立 access_log
在 server 块或 upstream 上游配置中,为常见静态后缀设置专用 location,并关闭默认日志,只记录到自定义日志文件:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|pdf|zip|tar|gz)$ {
# 静态资源通常不需重写或代理,直接由 Nginx 发送
expires 1y;
add_header Cache-Control "public, immutable";
<pre class="brush:php;toolbar:false;"># 关键:只记录到 static_access.log,不写入主 access_log
access_log /var/log/nginx/static_access.log main;
log_not_found off; # 避免 404 静态文件刷屏日志}
说明:
-
~*表示大小写不敏感正则匹配;可根据实际扩展后缀列表 -
main是 Nginx 默认日志格式名,也可自定义(见下文) - 确保该 location 在
location /或 proxy_pass 规则之前,避免被覆盖
2. 自定义日志格式,精简静态资源日志字段
静态资源访问量大,日志冗余会快速占满磁盘。建议定义轻量格式,只保留关键信息:
log_format static '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';然后在 location 中调用:
access_log /var/log/nginx/static_access.log static;
对比默认 main 格式,这里去掉了 $http_x_forwarded_for 等非必需字段,更利于日志解析与存储。
3. 排除干扰:跳过 robots.txt、favicon.ico 和健康检查请求
这些请求虽带静态后缀,但不属于真实资源访问,应排除统计:
location = /robots.txt {
access_log off;
log_not_found off;
return 200 "User-agent: *\nDisallow: /\n";
}
<p>location = /favicon.ico {
access_log off;
log_not_found off;
try_files /favicon.ico =204;
}</p><h1>常见健康检查路径(如 /healthz),也建议关闭日志</h1><p>location = /healthz {
access_log off;
return 200 "ok";
}注意:location = 是精确匹配,优先级高于正则,可安全放在静态资源 location 之前或之后。
4. 日志轮转与清理(防止磁盘打满)
静态日志增长极快,务必配置 logrotate:
/var/log/nginx/static_access.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0644 www-data www-data
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}保存为 /etc/logrotate.d/nginx-static,并测试:logrotate -d /etc/logrotate.d/nginx-static。
这样配置后,所有静态资源访问都会集中写入 static_access.log,无杂项干扰,字段清晰,支持高效聚合分析。后续可用 awk '{print $7}' static_access.log | sort | uniq -c | sort -nr | head -20 快速查看热门资源。










