Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置

我们在学些apache的时候已经接触过访问日志,还记得日志格式在哪里定义吗,在httpd的主配置文件中,/usr/lcoal/apache2.4/conf/httpd.conf 搜索LogFormat 就可以查看到,系统给了我们两种格式,combined 和common 我们选择使用了combined ,它记录的信息更全面。接下来我们在虚拟主机配置文件中定义了日志所在路径及类型。/usr/local/apache2.4/conf/extra/httpd-vhosts.conf

1访问日志

在nginx 住配置文件件中搜索Log_format获取到日志格式信息
cat /usr/local/nginx/conf/nginx.conf |grep -A2 log_format
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置
各字段含义为:
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置
其中紧跟log_format后面的 nginxlog 为日志格式的名字,后面要调用它。
接下来我们去虚拟主机配置文件中指定访问日志的路径。也就是在原有虚拟主机配置文件里加入一行内容:acces_log /tmp/nginx_accesslog nginxlog;

vim /usr/local/nginx/conf/vhost/test.com.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;
    }
    acces_log /tmp/nginx_access.log nginxlog;
}

-t -s reload 测试
访问一个不存在的网页
curl -x127.0.0.1:80 test.com/sdfsdf
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置

2 日志切割

nignx的访问日志不像apache自带切割工具,因此我们要定义一个日志切割脚本来实现日志切割。

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"
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
done
/bin/kill -HUP `cat $nginx_pid`

备注:
kill -HUP pid
pid 是进程标识。如果想要更改配置而不需停止并重新启动服务,请使用该命令。在对配置文件作必要的更改后,发出该命令以动态更新服务配置。根据约定,当您发送一个挂起信号(信号 1 或 HUP)时,大多数服务器进程(所有常用的进程)都会进行复位操作并重新加载它们的配置文件
我们运行下脚本,查看下是否切割

sh /usr/local/sbin/nginx_log_rotate.sh
ls /tmp/*log*

Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置

3 配置静态文件不记录日志,配置缓存过期时间

需求跟httpd一样,但是配置就简单许多了。将虚拟主机配置文件更改为如下:

server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
     {
          expires      7d;
          access_log off;
    }
   location ~ .*\.(js|css)$
    {
          expires      12h;
          access_log off;
    }
}

echo "1111111111" > /data/wwwroot/test.com/1.js //模拟一个js文件
echo "22222222222" > /data/wwwroot/test.com/2.jpg //模拟一个jpg文件
touch /data/wwwroot/test.com/1.jss //创建一个对比文件,不属于以上配置
curl -x127.0.0.1:80 test.com/1.js -I
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置
curl -x127.0.0.1:80 test.com/2.jpg -I
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置
curl -x127.0.0.1:80 test.com/1.jss -I
Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置
我们从从前两个的访问结果可以看到出现了max-age这一项,就是我们前面定义的缓存有效时长,单位是秒。最有一个jss文件不在配置内,所以没有这一项。
最后我们看下访问日志,发现js和jpg文件的访问都没有记录。

Linux学习总结(四十一)nginx 访问日志配置,网页缓存有效期配置

猜你喜欢

转载自blog.51cto.com/12606610/2107912
今日推荐