Nginx优化与防盗链
Nginx优化与防盗链
前言
为了适应企业需求,就需要考虑如何提升Nginx的性能与稳定性,这就是Nginx优化的内容,本次博客主要讲述Nginx的优化以及防盗链的部署。
一、隐藏版本号
1.1、隐藏Nginx版本号,避免安全漏洞泄露
1.2、Nginx隐藏版本号的方法
未隐藏版本号前使用curl -I(大写的i)命令检测结果
1 [root@localhost ~]# curl -I http://20.0.0.10
2 HTTP/1.1 200 OK
3 Server: nginx/1.12.2
4 Date: Fri, 16 Oct 2020 06:15:34 GMT
1 vi /usr/local/nginx/conf/nginx.conf
2 http {
3 include mime.types;
4 default_type application/octet-stream;
5
6 server_tokens off; ###关闭版本号
7 [root@localhost ~]# systemctl restart nginx
8
9 [root@localhost ~]# curl -I http://20.0.0.10
10 HTTP/1.1 200 OK
11 Server: nginx
12 Date: Fri, 16 Oct 2020 06:25:37 GMT
1 [root@localhost ~]# vi /root/nginx-1.12.2/src/core/nginx.h
2 #define nginx_version 1012002
3 #define NGINX_VERSION "1.1.1" ###修改版本号
4 #define NGINX_VER "jh/" NGINX_VERSION
5
6 [root@localhost nginx-1.12.2]# make && make install
7
8 [root@localhost ~]# curl -I http://20.0.0.10
9 HTTP/1.1 200 OK
10 Server: nginx/1.1.1
二、修改Nginx用户和组
2.1、Nginx运行时进程需要有用户与组的支持,以实现对网站文件读取时进行访问控制
2.2、Nginx默认使用nobody用户账号与组账号
2.3、修改的方法
编译安装时指定用户与组
1 [root@localhost ~]# vi /usr/local/nginx/conf/nginx.conf
2 user nginx nginx;
3
4 [root@localhost ~]# systemctl restart nginx
5 [root@localhost ~]# ps aux | grep nginx ###查看进程信息
三、配置Nginx网页缓存时间
3.1、当nginx将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容的请求时直接返回,避免重复请求,加快了访问速度。
3.2、一般针对静态网页设置,对动态网页不设置缓存时间
3.3、设置方法
在主配置文件的location段加入expires参数
1 [root@localhost ~]# vi /usr/local/nginx/conf/nginx.conf
2 location / {
3 root html;
4 index index.html index.htm;
5 expires 1d; ###设置缓存时间为1天
6 }
7
8 [root@localhost ~]# systemctl restart nginx
四、实现Nginx的日志切割
4.1、随着Nginx运行时间增加,日志也会增加。太大的日志文件对监控是一个大灾难。所以需要定期进行日志文件的切割
4.2、Nginx自身不具备日志分割处理的功能,但可以通过Nginx信号控制功能的脚本实现日志的自动切割(Kill -HUP cat /xxx/log/nginx.pid #平滑重启nginx,类似reload)
-QUIT :结束进程;-USR1:日志分割;-USR2:平滑升级
4.3、通过Linux的计划任务周期性地进行日志切割
4.4、编写脚本进行日志切割示例
1 [root@localhost ~]# vi /usr/local/nginx/conf/nginx.conf
2 error_log logs/error.log info;
3
4 log_format main '$remote_addr - $remote_user [$time_local] "$request" '
5 '$status $body_bytes_sent "$http_referer" '
6 '"$http_user_agent" "$http_x_forwarded_for"';
7
8 access_log logs/access.log main; ###去除前面#号
9
10 [root@localhost ~]# nginx -t ###检查配置文件是否正确
11 nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
12 nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
13
14 [root@localhost ~]# vim fenge.sh
15 #!/bin/bash
16 #Filename:fenge.sh
17 d=$(date -d "-1 day" "+%Y%m%d")
18 logs_path="/var/log/nginx"
19 pid_path="/usr/local/nginx/logs/nginx.pid" ###设置日期及路径变量
20 [ -d $logs_path ] || mkdir -p $logs_path ###自动创建日志目录
21 mv /usr/local/nginx/logs/access.log ${logs_path}/test.com-access.log-$d ###分割新的日志
22 kill -HUP $(cat $pid_path) ###生成新的日志
23 find $logs_path -