Nginx优化服务 ---- 进程管理、日志分割、压缩
一:日志分割
随着 Nginx运行时间的增加,产生的日志也会增加,需要定期地进行日志文件的切割。Nginx自身不具备日志分割处理的功能,但可以通过Nginx信号控制功能的脚本实现日志的自动切割,并通过Linux的计划任务周期性地进行日志切割 。
1、编写脚本实现分割
[root@localhost opt]# vim fenge.sh
#!/bin/bash
#filename:fenge.sh
d=$(date -d "-1 day" "+%Y%m%d")
logs_path="/var/log/nginx"
pid_path="/usr/local/nginx/logs/nginx.pid"
[ -d $logs_path ] || mkdir -p $logs_path ‘检测是否存在日志文件目录,没有就创建’
mv /usr/local/nginx/logs/access.log ${logs_path}/test.com-access.log-$d ‘移动并重新命名日志文件’
kill -USR1 $(cat $pid_path) ‘重建新的日志文件’
find $logs_path -mtime +30 | xargs rm -rf '删除30天之前的日志文件'
2、执行脚本,测试日志文件是否分割
[root@localhost opt]# chmod +x fenge.sh
[root@localhost opt]# ./fenge.sh
[root@localhost opt]# cd /var/log/nginx
[root@localhost nginx]# ls
test.com-access.log-20191225 ‘昨天的日志文件被分割出来了’
[root@localhost nginx]# date -s 2019-12-27 ‘把时间往后移一天’
2019年 12月 27日 星期四 00:00:00 CST
[root@localhost opt]# ./fenge.sh
[root@localhost opt]# cd /var/log/nginx/
[root@localhost nginx]# ls
test.com-access.log-20191225 test.com-access.log-20191226 ‘就会看到前两天的日志分割’
[root@localhost nginx]# cd /usr/local/nginx/logs
[root@localhost logs]# ls
access.log error.log nginx.pid
‘自动产生’
3、 还可以设置crontab,定期执行脚本自动进行日志分割
crontab -e
0 1 * * * /opt/fenge.sh
‘表示每天凌晨一点执行 fenge.sh脚本,进行日志分割’
二:进程管理 (设置连接超时)
在企业网中,为了避免同一个客户长时间占用连接,造成资源浪费,可设置相应的连接超时参数,实现对连接访问时间的控制 。
[root@localhost ~]# cd /usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf ‘修改配置文件,设置超时时间’
在客户机win10抓包验证
三:网页压缩
Nginx的ngx_http_gzip_module压缩模块提供对文件内容压缩的功能;
允许Nginx服务器将输出内容在发送客户端之前进行压缩,以节约网站带宽,提升用户的访问体验,默认已经安装;
可在配置文件中加入相应的压缩功能参数对压缩性能进行优化。
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
36 gzip on; ‘开启gzip压缩功能’
37 gzip_min_length 1k; ‘压缩阈值’
38 gzip_buffers 4 16k; ‘buffer大小为4个16k缓冲区大小’
39 gzip_http_version 1.1; ‘压缩版本’
40 gzip_comp_level 6; ‘压缩比率’
41 gzip_types text/plain application/x-javascript text/css image/jpg image/png image/gif application/xml text/javascript application/x-httpd-php application/javascript application/json;
42 gzip_disable "MSIE [1-6]\."; ‘配置禁用gzip条件,支持正则,表示ie6以下不启用gzip’
43 gzip_vary on; ‘选择支持vary header可以让前端的缓存服务器缓存经过gzip压缩的页面’
我们将图片放入站点目录中,并将图片写入nginx服务器的默认网页中
[root@localhost nginx]# cd html/
[root@localhost html]# ls
50x.html dog.jpg index.html ‘可以看到dog.jpg ’
[root@localhost html]# vim index.html
[root@localhost html]# service nginx stop
[root@localhost html]# service nginx start
用抓包工具检测,是否压缩成功