Created
January 8, 2019 23:26
-
-
Save kn007/625007685e0346e03a0bbf412c0703ef to your computer and use it in GitHub Desktop.
Add convert image to webp support for nginx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------------------- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://kn007.net/topics/add-convert-image-to-webp-support-for-nginx/