为什么要进行压缩?
在企业中,nginx服务器占用的资源要尽可能的少一些,而实际上网页和高清图片占用的资源是非常大的,这样不利于服务器的优化,因此需要进行压缩,可户可根据自己的需要自行下载。
一、网页文字的压缩
为了实验效果明显,在nginx的默认发布目录(/usr/local/nginx/html/index.html)多写点东西。
未压缩时:
cd /usr/local/nginx/conf
vim nginx.conf
gzip on; #打开压缩
gzip_min_length 1; #小于1kb不压缩
gzip_comp_level 2; #压缩等级2,压缩级别越大,越不清楚
gzip_types text/plain text/css image/jpeg application/x-javasript ; #压缩类型
systemctl restart nginx #重启服务
检测已被压缩:
二 、对客户端的访问控制
1.设置访问的并发量
cd /usr/local/nginx/conf/
vim nginx.conf
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 1;
}
systemctl restart nginx
客户端测试:ab -c 100 -n 1000 http://172.25.7.1/download/77.png
2.设置访问速率
cd /usr/local/nginx/conf/
vim nginx.conf
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 1;
limit_rate 444k;
}
systemctl restart nginx
配置文件:
客户端测试:
三、图片压缩
图片压缩前访问网页:
要想实现压缩,首先需要加载图像模块,然后修改配置文件并重启服务。
1 cd ~/nginx-1.16.1 #进入nginx安装包模块
2 ./configure --help | grep image #搜寻一下图像模块
3 ./configure --prefix=/usr/local/nginx/ --with-http_image_filter_module=dynamic #检测,看是否缺少包
4. 缺少gd-devel,去pkgs网站下载一个
5. yum install gd-devel -y #安装
6. ./configure --prefix=/usr/local/nginx/ --with-http_image_filter_module=dynamic #再次检测
7. make && make install #安装
8. cd /usr/local/nginx/moduels #查看一下,会有image模块
9. mkdir /usr/local/nginx/html/download #建立一个目录存放测试图片
10. vim /usr/local/nginx/conf/nginx.conf 修改配置文件
11. systemctl restart nginx #重启服务
3 . 第一次检测:
检测结果缺少gd包:
4.网站上搜索下载:
5.下载后安装:
6.再次./configure检测发现没有报错,接下来可以make安装了:
7.安装
8. cd /usr/local/nginx/moduels #查看一下,会有image模块
9.mkdir /usr/local/nginx/html/download #建立一个目录,并在此目录存放测试图片
10.修改配置文件:
cd /usr/local/nginx/
vim conf/nginx.conf
11.重启服务:
再次访问网页,发现大小已变小。