Skip to content

Instantly share code, notes, and snippets.

@fireball2018
Last active December 23, 2015 10:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fireball2018/6618852 to your computer and use it in GitHub Desktop.
Save fireball2018/6618852 to your computer and use it in GitHub Desktop.
使用nginx+lua+ImageMagick实现自动缩略图
server {
listen 80;
server_name pic.example.com;
root /path_to/images;
location / {
index index.html;
}
location ~ (.*)!(t|c|tx)(\d+)(x(\d+))?.(gif|jpg|jpeg|png)$ {
root /path_to/thumbs;
set $image_root /path_to/images;
set $thumb_root /path_to/thumbs;
set $file "$thumb_root$uri";
default_type 'image/jpeg';
if (!-f $request_filename) {
rewrite_by_lua '
file_exists = function(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
get_path=function(str,sep)
sep=sep or "/";
return str:match("(.*"..sep..")");
end
local index = string.find(ngx.var.uri, "!");
local originalUri = string.sub(ngx.var.uri, 0, index-1);
local size = string.sub(ngx.var.uri, index+1);
local mode = string.sub(size, 0, 1);
index = string.find(size, "%.");
size = string.sub(size, 2, index-1);
if file_exists(ngx.var.image_root .. originalUri) then
local command = "";
if mode == "t" then
command = "convert " .. ngx.var.image_root .. originalUri .. " -resize \'" .. size .. ">\' " .. ngx.var.file;
elseif mode == "c" then
command = "convert " .. ngx.var.image_root .. originalUri .. " -thumbnail " .. size .. "^ -gravity center -extent " .. size .. " " .. ngx.var.file;
end
os.execute("mkdir -p " .. get_path(ngx.var.file));
os.execute(command);
ngx.req.set_uri(ngx.var.uri, true);
else
ngx.exit(404);
end
';
}
expires 30d;
}
location ~ .*\.(jpg|jpeg|gif|css|png|js|ico|swf|xml)$ {
expires 30d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment