Nginx访问日志&Nginx日志切割&静态文件不记录日志和过时时间

12.10 Nginx访问日志

日志格式

vim /usr/local/nginx/conf/nginx.conf //搜索log_format

$remote_addrphp

客户端IP(公网IP)css

$http_x_forwarded_forhtml

代理服务器的IPlinux

$time_localnginx

服务器本地时间shell

$hostvim

访问主机名(域名)bash

$request_uri服务器

访问的url地址curl

$status

状态码

$http_referer

访问前的源地址

$http_user_agent

用户代理

修改虚拟主机配置文件

除了在主配置文件nginx.conf里定义日志格式外,还须要在虚拟主机配置文件中进行修改

server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
   access_log /tmp/1.log lemlog;    //这里的lemlog就是在nginx.conf中定义的日志格式名字
}

检测&从新加载配置

-t
-s reload

效果测试

[root@linux-10 ~]# curl -x 127.0.0.1:80 test.com -I
HTTP/1.1 200 OK
Server: nginx/1.14.0
Date: Sat, 09 Jun 2018 02:47:16 GMT
Content-Type: text/html
Content-Length: 27
Last-Modified: Fri, 08 Jun 2018 04:35:18 GMT
Connection: keep-alive
ETag: "5b1a0786-1b"
Accept-Ranges: bytes

[root@linux-10 ~]# cat /tmp/1.log 
127.0.0.1 - [09/Jun/2018:10:47:16 +0800] test.com "/" 200 "-" "curl/7.29.0"

12.11 Nginx日志切割

Nginx日志切割可经过编写shell脚本的方式实现

自定义shell 脚本

vim /usr/local/sbin/nginx_log_rotate.sh
#! /bin/bash
d=`date -d "-1 day" +%Y%m%d`    //定义日期,由于是切割前一天的日志,通常为零点切割,因此日期定义为前一天
logdir="/tmp/"                  //定义日志存放位置
nginx_pid="/usr/local/nginx/logs/nginx.pid"  //获取Nginx的pid,为了让脚本实现Nginx从新加载
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
done
/bin/kill -HUP `cat $nginx_pid`              //Nginx从新加载,生成新的配置文件

任务计划

编写任务计划,规定日志切割的时间(shell脚本的执行时间)

0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh

12.12 静态文件不记录日志和过时时间

修改虚拟主机配置文件

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$      //匹配相关文件
      {
          expires      7d;                      //配置过时时间
          access_log off;                       //不记录日志
      }
   location ~ .*\.(js|css)$
      {
          expires      12h;
          access_log off;
      }

结果测试

建立测试文件并测试效果

[root@linux-10 ~]# curl -x 127.0.0.1:80 test.com/123.png
afdsfsfsdfsdfsddfs
[root@linux-10 ~]# curl -x 127.0.0.1:80 test.com
“This is a test site.”
[root@linux-10 ~]# cat /tmp/1.log 
127.0.0.1 - [09/Jun/2018:10:47:16 +0800] test.com "/" 200 "-" "curl/7.29.0"

日志只记录了访问主页的行为。

相关文章
相关标签/搜索