利用 Nginx 日志在 CentOS 上提升性能的实操方案
一 日志写入性能优化
log_format perf '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$request_time $upstream_response_time $pipe';
access_log /var/log/nginx/access.log perf buffer=32k flush=1m;
error_log /var/log/nginx/error.log warn;
关键字段说明:$request_time(请求总耗时)、$upstream_response_time(上游耗时)、$pipe(是否流水线)。缓冲写入可显著降低系统调用频率。location ~* \.(js|css|jpg|jpeg|gif|png|ico|bmp|svg|woff2?)$ {
access_log off;
expires 1y;
add_header Cache-Control "public, immutable";
}
location /healthz {
access_log off;
return 200 "OK";
}
access_log /var/log/nginx/access.log perf buffer=64k gzip flush=5m;
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;
以上做法通过减少日志体积、降低写入次数与优化文件句柄管理,直接提升请求处理路径的性能与稳定性。
二 日志轮转与存储策略
/var/log/nginx/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 nginx adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
要点:切割后通过 USR1 信号通知 Nginx 重新打开日志文件,避免继续写入已重命名的旧文件。#!/usr/bin/env bash
LOGS_PATH=$1
YESTERDAY=$(date -d "yesterday" +%F)
mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${YESTERDAY}.log
kill -USR1 $(cat /var/run/nginx.pid 2>/dev/null || pgrep -x nginx)
find ${LOGS_PATH} -name "access_*.log" -mtime +30 -delete
三 基于日志的指标分析与配置调优
awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -5
awk '$NF > 1 {print $0}' /var/log/nginx/access.log | sort -kNF -nr | head
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED
四 安全与合规要点
location ~ ^/static/.*\.(php|php5|sh|pl|py)$ { deny all; }
location ~ ^/images/.*\.(php|php5|sh|pl|py)$ { deny all; }
location /admin/ { return 404; }
location /templates/ { return 403; }