NGINX+Lua=Size_img

Изменение размера картинки на лету в nginx

Вариант №1 с возможностью упасть в ошибку

nginx.conf
  location / {
    lua_code_cache on;
    try_files $uri @invalid;
    content_by_lua_block {
      local magick = require("magick")
      local images_dir = "/some-dir-in-dir-images"
      local function return_not_found(msg)
        ngx.status = ngx.HTTP_NOT_FOUND
        ngx.header["Content-type"] = "text/html"
        ngx.say(msg)
        ngx.exit(0)
      end
      ngx.header["Content-Type"] = "image/jpeg;"
      local w, h, path = ngx.var.arg_w, ngx.var.arg_h, ngx.var.uri
      if w == nil or h == nil then
        return_not_found("invalid signature")
      end
      local size = w .. "x" .. h
      local source_fname = images_dir .. path
      ngx.print(magick.thumb(source_fname, size))
    }
  }
  location @invalid {
      content_by_lua_block {
        ngx.status = ngx.HTTP_BAD_REQUEST
      }
  }

Вариант №2 при не заданных параметрах, подставляет оригинал

Вариант 3 с учетом важности заданного параметра

Вариант 3.1 с использованием функции

Exampel url:

http://localhost/some-dir-in-dir-images/images?w=100&h=100

Last updated