Nginx日志导致带宽消耗大的处理方案
先厘清“带宽”与“日志量”的关系
降低日志写入量的配置优化
减少网络带宽占用的内容优化
日志运维与架构优化
可直接使用的配置片段
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/access.log main buffer=32k flush=5m if=$loggable;
error_log /var/log/nginx/error.log warn;
server {
listen 443 ssl http2;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 静态资源:关闭访问日志 + 长缓存
location ~* \.(?:jpg|jpeg|gif|png|ico|woff2|js|css)$ {
access_log off;
expires 1M;
add_header Cache-Control "public";
}
location / {
proxy_pass http://backend;
# 可按需添加: proxy_cache、gzip 等
}
}
}
log_format simple '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log simple buffer=16k flush=1m;
access_log syslog:server=127.0.0.1:514,tag=nginx fluentd;
# 或仅输出必要字段
log_format fluentd '{"time":"$time_iso8601","remote_addr":"$remote_addr",'
'"request":"$request","status":$status,"bytes_sent":$bytes_sent}';
access_log syslog:server=127.0.0.1:514,tag=nginx fluentd;
/var/log/nginx/*.log {
daily
rotate 14
missingok
compress
delaycompress
notifempty
create 0640 www-data www-data
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}