发布于 4年前

nginx日志格式以及关闭对静态资源的日志记录

日志格式

nginx默认的日志格式为:

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

log_format 要放到 http 段里面,并且要放到 server 段的外部

日志变量说明:

  • $scheme 请求的协议,http或https
  • $host 访问域名
  • $remote_user 远程客户端的用户名称,basic认证用户,没有时为“-”
  • $remote_addr 客户端IP地址
  • $time_local 访问时间和时区
  • $request 请求方法、请求uri和请求http协议
  • $status 响应状态码
  • $upstream_status upstream状态
  • $upstream_response_time 请求时upstream的响应时间
  • $request_time 整个请求的总时间,包括从读取客户端第一个字节到响应完成并写完日志的全部时间
  • $bytes_sent 返回给客户端大小
  • $body_bytes_sent 返回给客户端的body大小
  • $http_referer 请求来源
  • $http_user_agent 用户终端浏览器的UserAgent
  • $http_x_forwarded_for 通过代理服务器来记录的客户端的ip地址

自定义日志格式:

log_format main '$remote_addr $status $remote_user [$time_local] $host "$request" '
        '$upstream_status $request_time $upstream_response_time $bytes_sent $body_bytes_sent '
        '"$http_referer" "$http_user_agent" $http_x_forwarded_for';

设置access_log的存放路径,默认格式为main

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

静态资源访问记录不写入日志

静态资源,如js,css及各种图片,如果都记录到日志,会产生挺大的干扰,可关闭这些文件类型的日志,配置如下:

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
    expires      30d;
    access_log off;
}
location ~ .*\.(js|css)?$ {
    expires      1d;
    access_log off;
}
©2020 edoou.com   京ICP备16001874号-3