一、網頁壓縮
在實際的應用中,我們爲了使nginx上的資源儘可能的少佔用,而大量的高清的圖片與含有信息量大的網頁會佔用我們非常多的資源。這不利於nginx的性能優化,爲了解決這個問題,我們可以做 Gzip壓縮。
Nginx性能優化功能: Gzip壓縮(大幅度提高頁面加載速度) ,開啓Gzip壓縮功能, 可以使網站的css、js 、xml、html 文件在傳輸時進行壓縮,提高訪問速度,進而優化Nginx性能。經過Gzip壓縮後頁面大小可以變爲原來的30%甚至更小,這樣,用戶瀏覽頁面的時候速度會快得多。Gzip的壓縮頁面需要瀏覽器和服務器雙方都支持,實際上就是服務器端壓縮,傳到瀏覽器後瀏覽器解壓並解析。瀏覽器那裏不需要我們擔心,因爲目前的巨大多數瀏覽器 都支持解析Gzip過的頁面。
1、修改配置文件/usr/local/nginx/conf/nginx.conf
33 gzip on;
# 開啓gzip壓縮功能
34 gzip_min_length 1;
# 設置允許壓縮的頁面最小字節數;
35 gzip_comp_level 2;
# 設置壓縮比率,最小爲1,處理速度快,傳輸速度慢;9爲最大壓縮比,處理速度慢,傳輸速度快; 這裏表示壓縮級別,可以是0到9中的任一個,級別越高,壓縮就越小,節省了帶寬資源,但同時也消耗CPU資源,所以一般折中爲6
36 gzip_types text/plain application/x-javascript test/css application/xml vascript applic ation/x-httpd/php image/gif image/png;
#制定壓縮的類型,線上配置時儘可能配置多的壓縮類型
2、編輯nginx的默認發佈文件/usr/local/nginx/html/index.html
[root@server2 html]# ls
50x.html index.html
[root@server2 html]# pwd
/usr/local/nginx/html
[root@server2 html]# cp /etc/passwd .
[root@server2 html]# ls
50x.html index.html passwd
[root@server2 html]# du -sh passwd
4.0K passwd
[root@server2 html]# vim passwd
[root@server2 html]# du -sh passwd
44K passwd
[root@server2 html]# mv passwd index.html
mv: overwrite ‘index.html’? y
[root@server2 html]# du -sh index.html
44K index.html
3、然後在網頁查看大小(按下F12,之後選擇Network->Size,便可以查看到其文件大小)
4、重啓服務nginx -s reload
,清除緩存,再次查看
二、圖片壓縮
1、停止服務,重新編譯。添加新的模塊
[root@server2 nginx-1.15.9]# make clean
[root@server2 nginx-1.15.9]# ./configure \
> --prefix=/usr/local/nginx \
> --pid-path=/var/run/nginx/nginx.pid \
> --lock-path=/var/lock/nginx.lock \
> --error-log-path=/var/log/nginx/error.log \
> --http-log-path=/var/log/nginx/access.log \
> --with-http_realip_module --with-http_image_filter_module=dynamic
[root@server2 nginx-1.15.9]# make
[root@server2 nginx-1.15.9]# cd objs/
[root@server2 objs]# ls
autoconf.err nginx.8 ngx_http_image_filter_module_modules.c ngx_modules.c
Makefile ngx_auto_config.h ngx_http_image_filter_module_modules.o ngx_modules.o
nginx ngx_auto_headers.h ngx_http_image_filter_module.so src
[root@server2 objs]# cp nginx -f /usr/local/nginx/sbin/nginx
#將新的二進制文件替換成之前的二進制文件
cp: overwrite ‘/usr/local/nginx/sbin/nginx’? y
[root@server2 objs]# mkdir /usr/local/nginx/modules
#創建新的目錄,並將圖像模塊放在目錄下
[root@server2 objs]# cp ngx_http_image_filter_module.so /usr/local/nginx/modules
2、編輯nginx配置文件/usr/local/nginx/conf/nginx.conf
,重新加載。
1 load_module modules/ngx_http_image_filter_module.so;
47 location /search/ {
48 image_filter resize 50 100;
49 }
3、測試
在上面的共享圖片中我們可以得知,在瀏覽器中查詢時必須得輸入完整的路徑,其中包括圖片的名稱,可是這樣顯然是不合理的,我們認爲將圖片都放置一個目錄下,通過查看目錄選擇圖片纔是一種不錯的方式