文章目录
- 引言
- 一、Nginx 服务优化
- 1. 隐藏版本号
- 1.1 网页查看 Nginx 版本
- 1.2 命令查看 Nginx 版本
- 1.3 修改配置文件方式
- 1.4 修改源码文件,重新编译安装
 
- 2. 修改 Nginx 用户与组
- 2.1 编译安装时指定
- 2.2 修改配置文件方式
 
- 3. 配置网页缓存时间
- 4. 日志分割
- 5. 设置连接超时
 
- 二、Nginx深入优化
- 1. 更改进程数
- 2. 配网页压缩
- 2.1 压缩功能参数
- 2.2 压缩演示
 
- 3. 防盗链
 
- 总结
引言
  在企业信息化应用环境中,服务器的安全性和响应速度需要根据实际情况来进行相应的参数配置,来达到最优的用户体验。
 但是默认的Nginx安装参数只能提供最基础的服务,还需调整页面缓存时间、连接超时、网页压缩等相应参数,才能让 Nginx 发挥最大的性能,接受更高的并发。
一、Nginx 服务优化
1. 隐藏版本号
在生产环境中,需要隐藏 Nginx 版本号,以避免泄露 Nginx 的版本,使攻击者不能针对特定版本进行攻击。
1.1 网页查看 Nginx 版本
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d1qe6tvQ-1685697670563)(C:\Users\86138\AppData\Roaming\Typora\typora-user-images\image-20230602093329096.png)]](https://img-blog.csdnimg.cn/2cf66b1169e04a6ab00d0f6169a160b6.png#pic_center)
1.2 命令查看 Nginx 版本
[root@localhost ~]# curl -I http://192.168.145.45
HTTP/1.1 200 OK
Server: nginx/1.24.0						#版本信息
Date: Fri, 02 Jun 2023 05:59:25 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 02 Jun 2023 01:01:59 GMT
Connection: keep-alive
ETag: "64793f87-267"
Accept-Ranges: bytes
1.3 修改配置文件方式
[root@localhost ~]#vim /usr/local/nginx/conf/nginx.conf
.....
http {
    include       mime.types;
    default_type  application/octet-stream;
    ###添加,关闭版本号
    server_tokens off;	
......
###测试配置文件语法
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
###重启服务
[root@localhost conf]# systemctl restart nginx.service
###命令查看版本号
[root@localhost conf]# curl -I http://192.168.145.45
HTTP/1.1 200 OK
Server: nginx				#版本号被隐藏
Date: Fri, 02 Jun 2023 06:07:54 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 02 Jun 2023 01:01:59 GMT
Connection: keep-alive
ETag: "64793f87-267"
Accept-Ranges: bytes

1.4 修改源码文件,重新编译安装
[root@localhost ~]# vim /opt/nginx-1.12.0/src/core/nginx.h
#define NGINX_VERSION      "2.4.6"				 		#修改版本号
#define NGINX_VER          "apache/" NGINX_VERSION	 	#修改服务器类型
[root@localhost ~]# cd /opt/nginx-1.24.0/
[root@localhost nginx-1.24.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module
[root@localhost nginx-1.24.0]# make -j2 && make install
[root@localhost nginx-1.24.0]# vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens on;									 #开启版本号
	......
}
###测试配置文件语法
[root@localhost nginx-1.24.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
###重启服务
[root@localhost nginx-1.24.0]# systemctl restart nginx.service
[root@localhost nginx-1.24.0]# curl -I http://192.168.145.45
HTTP/1.1 200 OK
Server: apache/2.4.6									 #查看设置的版本信息
Date: Fri, 02 Jun 2023 06:20:18 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 02 Jun 2023 01:01:59 GMT
Connection: keep-alive
ETag: "64793f87-267"
Accept-Ranges: bytes
2. 修改 Nginx 用户与组
Nginx 运行时进程需要有用户与组的支持,用以实现对网站文件读取时进行访问控制。主进程由 root 创建,子进程由指定的用户与组创建。
Nginx 默认使用 nobody 用户账号与组账号,一般需要进行修改。修改 Nginx 用户和组有两种方法,一种是编译安装时指定用户和组,另一种是修改配置文件指定用户和组。
2.1 编译安装时指定
[root@localhost nginx-1.24.0]#./configure \
--prefix=/usr/local/nginx \
--user=nginx \   									#指定用户名是 nginx
--group=nginx \										#指定组名是 nginx
--with-http_stub_status_module
2.2 修改配置文件方式
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
###取消注释,修改用户为 nginx ,组为 nginx
user nginx nginx;
[root@localhost ~]# systemctl restart nginx.service 
###查看进程,主进程由root创建,子进程由nginx创建
[root@localhost ~]# ps aux | grep nginx
root      17901  0.0  0.0  20588   624 ?        Ss   14:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx     17902  0.0  0.0  23116  1384 ?        S    14:24   0:00 nginx: worker process
root      17906  0.0  0.0 112824   980 pts/3    S+   14:24   0:00 grep --color=auto nginx
3. 配置网页缓存时间
当 Nginx 将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容的请求时直接返回,避免重复请求,加快了访问速度。一般针对静态网页设置,对动态网页不设置缓存时间。
修改 Nginx 配置文件,在新的 location 段加入 expires 参数,指定缓存的时间,1d表示一天(若设置1.5天可指定为1d12h)
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
http {
......
	server {
	...... 
		location / {
			root html;
			index index.html index.htm;
		}
		###加入新的 location,以图片作为缓存对象
		location ~ \.(gif|jpg|jepg|png|bmp|ico)$ {
			root html;
			###指定缓存时间,1天
			expires 1d;	
		}
......
	}
}
[root@localhost ~]# systemctl restart nginx.service 
上传图片到 html 目录中,并修改站点文件
[root@local /usr/local/nginx]#cd html/
[root@local /usr/local/nginx/html]#ls
50x.html  index.html
 ###直接把图片拖进来,注意图片的格式!
[root@local /usr/local/nginx/html]#rz -E  
rz waiting to receive.
[root@local /usr/local/nginx/html]#ls
50x.html  hm.jpg  index.html
 
[root@local /usr/local/nginx/html]#vim index.html
......
<p><em>Thank you for using nginx.</em></p>
###23行位置插入识别图片
<img src="hm.jpg"/>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
......
浏览器访问页面

4. 日志分割
随着 Nginx 服务运行时间的增加,它的日志也会增加,为了能够方便知道 Nginx 的运行状态,需要时刻关注 Nginx 日志文件。过大的日志文件不利于日常监控和分析排查,因此需要定期的对日志文件进行切割。
Nginx 没有类似 Apache 的 cronlog 日志分割处理功能,但可以通过 Nginx 的信号控制功能脚本来实现日志的自动切割,并将脚本加入到 Linux 的计划任务中,让脚本在每天固定时间点执行,即可执行日志切割功能。
编写脚本
[root@localhost opt]# vim fengge.sh 
#!/bin/bash
#该脚本用于存放nginx服务三个月内的的分割日志
#定义变量获取当前时间前一天的时间格式
lastday=$(date -d "-1 day" +%Y-%m-%d)
#定义变量指定存放分割日志的目录
log_path="/var/log/nginx"
#定义变量指定nginx的工作目录
nginx_home="/usr/local/nginx"
#定义变量指定nginx服务的pid号文件路径
pid_path="$nginx_home/logs/nginx.pid
#############main################
#判断存放分割日志的目录是否存在,如若不存在则创建
if [ ! -d $log_path ];then
  mkdir -p $log_path
fi
#[ -d $log_path ] || mkdir -p $log_path
#执行日志分割操作,将访问/错误日志移动到指定目录/var/log/nginx/中,并以指定时间格式保存
mv $nginx_home/logs/access.log $log_path/access.log-$lastday
mv $nginx_home/logs/error.log $log_path/error.log-$lastday
#重建新日志文件
kill -USR1 $(cat $pid_path)
#删除90天(3个月)前的旧日志文件
find $log_path -mtime +90 | xargs rm -rf
执行脚本,测试日志文件是否被切割
[root@localhost opt]# chmod +x fengge.sh 
[root@localhost opt]# ./fengge.sh 
[root@localhost opt]# ls /var/log/nginx/
access.log-2023-06-01  error.log-2023-06-01
设置 crontab任务,定期执行脚本自动进行日志分割
[root@localhost /usr/local/nginx/logs]#crontab -e
 
0 1 * * * /opt/fengge.sh 
#每天凌晨 1:30 分执行/opt/fengge.sh  脚本,进行日志分割
小知识
在linux操作系统中,每个文件都有很多的时间参数,其中有三个比较主要,分别是ctime、atime、mtime。
- ctime(status time):当修改文件的权限或者属性的时候,就会更新这个时间,ctime并不是create time,更像是change time,
 只有当更新文件的属性或者权限的时候才会更新这个时间,但是更改内容的话是不会更新这个时间。
- atime(accesstime):当使用这个文件的时候就会更新这个时间。
- mtime(modification time):当修改文件的内容数据的时候,就会更新这个时间,而更改权限或者属性,mtime不会改变,这就是和ctime的区别。
5. 设置连接超时
在企业网站中,为了避免同一个客户长时间占用连接,造成资源的浪费,可以设置相应的连接超时参数,用来实现对连接访问时间的控制。
  HTTP有一个KeepAlive模式,它告诉web服务器在处理完一个请求后保持这个TCP连接的打开状态。若接收到来自同一客户端的其它请求,服务端会利用这个未被关闭的连接,而不需要再建立一个连接。KeepAlive 在一段时间内保持打开状态,它们会在这段时间内占用资源。占用过多就会影响性能。
修改 Nginx 配置文件
[root@localhost /opt]#vim /usr/local/nginx/conf/nginx.conf
 
http {
......
    #keepalive_timeout  0;
    keepalive_timeout  65;
    Client_header_timeout 80;           #等待客户端发送请求头的超时时间,超时会发送408错误
    Client_body_timeout 80;				#等待客户端发送请求体的超时时间
......
 
[root@localhost /opt]#nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
- Keepalive_timeout:指定KeepAlive的超时时间(timeout)。指定一个长连接最多可以保持多长时间,服务器将会在这个时间后关闭连接。 Nginx的默认值是65秒,有些浏览器最多只保持 60 秒,所以可以设定为 60 秒。若将它设置为0,就禁止了keepalive 连接。
 第二个参数(可选的)指定了在响应头Keep-Alive:timeout=time中的time值。这个头能够让一些浏览器主动关闭连接,这样服务器就不必去关闭连接了。没有这个参数,Nginx 不会发送 Keep-Alive 响应头。
- Client_header_timeout:客户端向服务端发送一个完整的 request header 的超时时间。如果客户端在指定时间内没有发送一个完整的 request header,Nginx 返回 HTTP 408(Request Timed Out)。
- Client_body_timeout:指定客户端与服务端建立连接后发送 request body 的超时时间。如果客户端在指定时间内没有发送任何内容,Nginx 返回 HTTP 408(Request Timed Out)。
浏览器访问页面

二、Nginx深入优化
1. 更改进程数
在高并发环境中,需要启动更多的 Nginx 进程以保证快速响应,用以处理用户的请求,避免造成阻塞。
查看nginx主进程中包含几个子进程
[root@localhost ~]# cat /proc/cpuinfo | grep -c "physical id"
2
[root@localhost ~]# ps anux | grep nginx
       0  74986  0.0  0.0  20588   628 ?        Ss   15:27   0:00 nginx: master process /usr/local/nginx/sbin/nginx
    1001  74987  0.0  0.0  23116  1636 ?        S    15:27   0:00 nginx: worker process
       0  75120  0.0  0.0 112828   976 pts/3    S+   15:39   0:00 grep --color=auto nginx
修改 Nginx 配置文件中的 work_processes 参数
一般设为 CPU 的个数或核数,在高并发的情况下可以设置为 CPU 个数或核数的2倍。
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;				#修改为核数相同或者2倍,或者atuo
worker_cpu_affinity 01 10;			#01表示启用第一个CPU内核,10表示启用第二个CPU内核,以此类推...
  设置每个进程由不同cpu处理,进程数配为4时 0001 0010 0100 1000。
将每个worker子进程与特定CPU物理核心绑定,提升cpu利用率,进而提升性能。避免同一个worker子进程在不同的CPU核心上切换或者多个进程跑在一个CPU上,缓存失效,降低性能。
重启服务,查看进程数
[root@localhost ~]# systemctl restart nginx.service 
[root@localhost ~]# ps anux | grep nginx
       0  75207  0.0  0.0  20588   632 ?        Ss   15:45   0:00 nginx: master process /usr/local/nginx/sbin/nginx
    1001  75208  0.0  0.0  23116  1392 ?        S    15:45   0:00 nginx: worker process
    1001  75209  0.0  0.0  23116  1392 ?        S    15:45   0:00 nginx: worker process
       0  75213  0.0  0.0 112824   980 pts/3    R+   15:45   0:00 grep --color=auto nginx
2. 配网页压缩
   Nginx 的 ngx_http_gzip_module 压缩模块提供了对文件内容压缩的功能,允许 Nginx 服务器将输出内容发送到客户端之前进行压缩,以节约网站的带宽,提升用户的访问体验。
默认 Nginx 已安装该模块,只需要在配置文件中加入相应的压缩功能参数对压缩性能进行优化即可。
2.1 压缩功能参数
| 参数 | 含义 | 
|---|---|
| gzip on | 开启gzip压缩输出。 | 
| gzip_min_length 1k | 设置允许压缩的页面最小字节数。 | 
| gzip_buffers 4 16k | 申请4个单位为16k的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。 | 
| gzip_http_version 1.0 | 设置识别http协议版本,默认是 1.1,目前大部分浏览器已经支持gzip解压,但处理较慢,也比较消耗服务器CPU资源。 | 
| gzip_comp_level 2 | 指定gzip压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度快,但处理速度最慢。 | 
| gzip_types text/plain | 压缩类型,对哪些网页文档启用压缩功能。 | 
| gzip_vary on | 让前端缓存服务器缓存经过gzip压缩的页面。 | 
2.2 压缩演示
设置压缩参数
[root@localhost /usr/local/nginx/conf]# vim /usr/local/nginx/conf/nginx.conf
http {
...... 
   gzip on;							#取消注释,开启gzip压缩功能
   gzip_min_length 1k;      		#最小压缩文件大小
   gzip_buffers 4 64k;      		#压缩缓冲区,大小为4个64k缓冲区
   gzip_http_version 1.1;   		#压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
   gzip_comp_level 6;       		#压缩比率
   gzip_vary on;					#支持前端缓存服务器存储压缩页面
   gzip_types text/plain text/javascript application/x-javascript text/css text/xml application/xml application/xml+rss image/jpg image/jpeg image/png image/gif application/x-httpd-php application/javascript application/json;		#压缩类型,表示哪些网页文档启用压缩功能
...... 
}
gzip on;					
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_vary on;
gzip_types text/plain application/x-javascript text/css image/jpg image/jpeg image/png image/gif application/xml text/javascript application/x-httpd-php application/javascript application/json;
上传图片到 /usr/local/nginx/html 目录下
[root@localhost /usr/local/nginx/conf]#cd /usr/local/nginx/html/
[root@localhost /usr/local/nginx/html]#ls
50x.html  index.html
[root@localhost /usr/local/nginx/html]#rz -E
rz waiting to receive.
[root@localhost /usr/local/nginx/html]#ls
50x.html  hm.jpg  index.html
在网页中插入图片
[root@local /usr/local/nginx/html]#vim index.html
......
<p><em>Thank you for using nginx.</em></p>
 ###23行位置插入识别图片
<img src="hm.png"/>                          
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
......
浏览器中访问网址
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-viybnmNt-1685697670565)(C:\Users\86138\AppData\Roaming\Typora\typora-user-images\image-20230602161924896.png)]](https://img-blog.csdnimg.cn/0f42a5f42a3c4500a644b5f8c5621911.png#pic_center)
3. 防盗链
盗链是一种恶意行为,在互联网上广泛存在,如果不了解什么是盗链,不采取一些方式防止盗链,网站经营者很有可能付惨重的代价,却得不到任何收益。那么什么是盗链?防止盗链又该如何操作呢?
环境配置
服务端:192.168.145.45 www.abc.com
盗链端: 192.168.145.30 www.def.com
盗链端配置
###设置域名和IP映射关系
[root@localhost ~]# vim /etc/hosts
192.168.145.45 www.abc.com
192.168.145.30 www.def.com
 
###在盗链端编写盗链页面index.html,盗取源主机的图片
[root@localhost ~]# vim /var/www/html/daolian.html 
<html>
<body>
<h1> this is dao lian</h1>
<img src="http://192.168.145.45/hm.jpg"/>
</body>
</html>
[root@localhost ~]# vim /etc/httpd/conf/httpd.conf 
###修改95行
ServerName www.def.com:80
###重启服务
[root@localhost ~]# systemctl restart httpd
服务端配置
###设置域名和IP映射关系
[root@localhost ~]#vim /etc/hosts
192.168.145.45 www.abc.com
192.168.145.30 www.def.com
###把图片放入html目录下
[root@localhost ~]# cd /usr/local/nginx/html/              
[root@localhost html ]# ls
50x.html  hm.png  error.png  index.html
[root@localhost html]# vim /usr/local/nginx/html/index.html
50x.html  hm.png  error.png  index.html
[root@localhost /usr/local/nginx/html]#vim index.html 
...
<img src="hm.jpg"/>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
</body>
</html>
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  www.abc.com;
		.....
        }
        location ~ \.(gif|jpg|jepg)$ {
            root html;
            expires 1d;
            valid_referers none blocked *.abc.com abc.com;
            if ( $invalid_referer ) {
                rewrite ^/ http://www.abc.com/error.png;
                #return 403;
            }
        }
        ......
        
###重启服务
[root@localhost ~]# systemctl restart nginx
- ~* \.(jpg|gif|swf)$:这段正则表达式表示匹配不区分大小写,以- .jpg或- .gif或.swf 结尾的文件;
- valid_referers:设置信任的网站,可以正常使用图片;
- none:允许没有http_refer的请求访问资源(根据Referer的定义,它的作用是指示一个请求是从哪里链接过来的,如果直接在浏览器的地址栏中输入一个资源的URL地址,那么这种请求是不会包含 Referer 字段的),如- http://www.abc.com/hm.jpg
- 我们使用 http:///www.abc.com访问显示的图片,可以理解成http://www.abc.com/hm.jpg这个请求是从http:///www.abc.com这个链接过来的。
- blocked:允许不是http://开头的,不带协议的请求访问资源;
- *.abc.com:只允许来自指定域名的请求访问资源,如- http:///www.abc.com
- if语句:如果链接的来源域名不在- valid_referers所列出的列表中,- $invalid_referer为true,则执行后面的操作,即进行重写或返回 403 页面。
浏览器测试,最后在盗链端查看进行验证,右击查看图片,选择查看属性可以看到成功盗取

总结
- Nginx配置文件组成: global全局模块配置;http{}模块配置; server模块; location 匹配URL和路径;
- Nginx擅长处理静态请求的服务,理论上能支持3~5万个并发请求,但受制于CPU个数和最大文件打开数;
- Nginx的优点是轻量级,功能比较丰富(开源&收费),缺陷是它默认情况下是不支持集群的;
- Nginx服务优化包括隐藏版本号、更改用户与组、配置网页缓存时间、日志切割、设置连接超时;
- 深入优化包括更改进程数、配置网页压缩、配置防盗链和FPM参数优化。



















