Skip to content

Instantly share code, notes, and snippets.

@kn007
Created January 8, 2019 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kn007/625007685e0346e03a0bbf412c0703ef to your computer and use it in GitHub Desktop.
Save kn007/625007685e0346e03a0bbf412c0703ef to your computer and use it in GitHub Desktop.
Add convert image to webp support for nginx
--------------------------- Function ---------------------------------
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
------------------------------------------------------------------------
if ngx ~= nil then
local reqpath = ngx.var.request_filename;
local requri = ngx.var.uri;
local originalFile = reqpath:sub(1, #reqpath - 13);
local originalFile_uri = requri:sub(1, #requri - 13);
if not file_exists(originalFile) then
ngx.exit(404);
return;
end
local newFile_md5 = ngx.md5(originalFile_uri);
local newFile = ngx.var.document_root .. "/wp-content/webp/" .. newFile_md5 ..".webp";
local newFile_uri = "/wp-content/webp/" .. newFile_md5 .. ".webp";
if file_exists(newFile) then
ngx.req.set_uri(newFile_uri);
ngx.exec(ngx.var.uri);
return;
end
os.execute("cwebp -quiet " .. originalFile .. " -o " .. newFile);
if file_exists(newFile) then
ngx.req.set_uri(newFile_uri);
else
ngx.req.set_uri(originalFile_uri);
end
ngx.exec(ngx.var.uri);
end
@kn007
Copy link
Author

kn007 commented Jan 8, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment