Nginx的ngx_http_image_filter_module
模塊(nginx版本爲0.7.54+) 可用來動態轉換JPEG, GIF, PNG, 和WebP格式的圖片大小。nginx
該模塊默認沒有構建,須要經過 --with-http_image_filter_module
配置參數啓用。vim
若是圖片訪問量不大,能夠使用該模塊。服務器
該模塊使用了libgd庫。 推薦使用該庫的最新版本。markdown
如下爲在已經安裝了nginx的狀況下添加該模塊的步驟。oop
yum -y install gd-devel
yum -y install libxslt-devel
yum -y install perl-devel perl-ExtUtils-Embed
複製代碼
nginx -V
測試
輸出結果以下:spa
nginx version: nginx/1.12.2
configure arguments:
查看是否有--with-http_image_filter_module,若是有則說明已經安裝過,不然繼續安裝。code
從新編譯時須要下載和原來相同版本的nginx源碼,解壓。orm
添加--with-http_image_filter_module=dynamic
及原來的參數(不須要執行make install命令從新安裝)圖片
./configure --with-http_image_filter_module=dynamic
make
複製代碼
cp -r /usr/local/nginx /usr/local/nginxbak
cp objs/nginx /usr/local/nginx/sbin/
mkdir /usr/local/nginx/module
cp objs/ngx_http_image_filter_module.so /usr/local/nginx/module/ngx_http_image_filter_module.so
複製代碼
vim /usr/local/nginx/conf/nginx.conf
load_module /usr/local/nginx/module/ngx_http_image_filter_module.so;
location ~* /images/(.+)_(\d+)x(\d+)\.(jpg|jpeg|gif|png)$ {
set $w $2;
set $h $3;
image_filter resize $w $h;
image_filter_buffer 30M; #設置圖片緩衝區的最大大小,大小超過設定值,服務器將返回錯誤415
image_filter_interlace on;
image_filter_jpeg_quality 80;
try_files /$1.$4 /notfound.jpg;
expires 1d;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
alias /home/publisherupload/ ; #root 可以讓訪問 /images/ 路徑時,訪問到 /User/XX/Desktop/images,若是將 root 替換爲 alias,則訪問的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本機中的絕對路徑。
}
location /images {
alias /home/publisherupload/ ; #root 可以讓訪問 /images/ 路徑時,訪問到 /User/XX/Desktop/images,若是將 root 替換爲 alias,則訪問的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本機中的絕對路徑。
autoindex on; #打開目錄瀏覽功能
}
複製代碼
/usr/local/nginx/sbin/nginx -s
最終的圖片訪問地址爲在原圖片地址後面加入_寬度X高度
參數
http://110.87.103.58:12345/images/2021-01/202101250944272_500x400.png