日志格式配置: 在nginx.conf中配置包含响应时间的日志格式:
log_format timed_combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
分析慢查询:
bash
awk '{if ($NF > 5) print $0}' /var/log/nginx/access.log | sort -k10 -nr
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
优化配置:
# 调整工作进程和连接数
worker_processes auto;
worker_connections 1024;
# 启用keepalive
keepalive_timeout 65;
keepalive_requests 100;
# 启用sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;
启用微缓存:
proxy_cache_path /tmp/nginx levels=1:2 keys_zone=microcache:10m max_size=100m inactive=60m;
location / {
proxy_cache microcache;
proxy_cache_valid 200 1m;
proxy_cache_bypass $http_cache_control;
add_header X-Proxy-Cache $upstream_cache_status;
}
负载均衡优化:
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
keepalive 32;
}
日志持续监控:
通过以上方法,您可以有效识别和解决Nginx日志中出现的慢查询问题,提升网站性能和用户体验。