Записки криворукого админа
  • Записки криворукого админа
  • SaltStack
    • State
      • Name active interface
      • watch, require, *_in
    • Salt-api
      • tokens
    • ERROR
      • No module named tornado.stack_context
      • Got a bad pillar from master
  • Jinja
    • Last comma
  • Python
    • проверка версии модуля
  • Gitlab
    • Example values CI
    • gitlab multi pipeline
  • Linux
    • qemu/kvm
    • Cron all user
    • OpenVPN GUI
    • Group Linux
    • passwd
    • Systemctl
    • chmod для взрослых ;)
    • Comand0s
      • disck
      • grep
      • link
      • mkdir
    • Supervisor
    • Изменение hostname
    • WiFi - broadcom
    • cockpit
    • Viber
    • Время в терминале
    • Chmod
    • Docker ?
    • Тмух
    • Количество ядер
  • Utility
    • scp
      • zsh: no matches found
    • rsyslog
      • stop not work
    • Vi/Vim
      • Hotkeys
    • parted
      • Create over 2TB partition
    • lsyncd
    • mdadm
      • /boot on RAID1
  • MySQL
    • Типы таблиц (ENGINE)
    • Доступ для пользователя
    • Xtrabackup
    • WSREP - help
    • Примитивы
  • NetWork
    • OpenVPN
    • Установка Pure-FTP
  • Ansiblya
    • unmanaged files
  • Restore
    • Safest way to clean up boot partition
  • Редис
    • High Performance Redis
  • SSL
    • API cloudflare
    • bundel
  • Apache
    • Nginx, Apache, REMOTE_ADDR 127.0.0.1
  • Openresty/Nginx
    • default, Not $host
    • NGINX+Lua=parser_ip
    • NGINX+Lua=Size_img
  • Mong0
  • Mac
    • VirtualBox
  • Hobby
    • 🖖XMage
Powered by GitBook
On this page
  1. Openresty/Nginx

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 при не заданных параметрах, подставляет оригинал

ngunx.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 w, h, path = ngx.var.arg_w, ngx.var.arg_h, ngx.var.uri
      local source_fname = images_dir .. path
      local img = magick.load_image(source_fname)
      if w == nil and h == nil then
        local w = img:get_width()
        local h = img:get_height()
        local size = w .. "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      if w == nil then
        local w = img:get_width()
        local size = w .. "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      if h == nil then
        local h = img:get_height()
        local size = w .. "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      local size = w .. "x" .. h
      if size == "x" then
        local w = img:get_width()
        local h = img:get_height()
        local size = w .. "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      ngx.header["Content-Type"] = "image/jpeg;"
      ngx.print(magick.thumb(source_fname, size))
    }
  }
  location @invalid {
      content_by_lua_block {
        ngx.status = ngx.HTTP_BAD_REQUEST
      }
  }

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

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 w, h, path = ngx.var.arg_w, ngx.var.arg_h, ngx.var.uri
      local source_fname = images_dir .. path
      local img = magick.load_image(source_fname)
      if w == nil and h == nil then
        local size = 0 .. "x" .. 0
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      elseif w == nil then
        local size = "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      elseif h == nil then
        local size = w .. "x"
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      local size = w .. "x" .. h
      if size == "x" then
        local w = img:get_width()
        local h = img:get_height()
        local size = w .. "x" .. h
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      ngx.header["Content-Type"] = "image/jpeg;"
      ngx.print(magick.thumb(source_fname, size))
    }
  }
  location @invalid {
      content_by_lua_block {
        ngx.status = ngx.HTTP_BAD_REQUEST
      }
  }

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

nginx.conf
  location / {
    add_header Cache-Control public;
    expires max;
    lua_code_cache on;
    try_files $uri @invalid;
    content_by_lua_block {
      local magick = require("magick")
      local md5 = require("md5")
      local images_dir = "/some-dir-in-dir-images"
      local w, h, path = ngx.var.arg_w, ngx.var.arg_h, ngx.var.uri
      local source_fname = images_dir .. path
      local function return_img(size)
        ngx.header["Content-Type"] = "image/jpeg;"
        ngx.header["ETag"] = md5.sumhexa(source_fname .. size)
        ngx.header.Last_Modified = os.date("%a, %d %b %Y %H:%M:%S GMT", os.time())
        ngx.print(magick.thumb(source_fname, size))
        ngx.exit(0)
      end
      if w == nil and h == nil then
        local size = 0 .. "x" .. 0
        return_img(size)
      elseif w == nil then
        local size = "x" .. h
        return_img(size)
      elseif h == nil then
        local size = w .. "x"
        return_img(size)
      end
      local size = w .. "x" .. h
      if size == "x" then
        local size = 0 .. "x" .. 0
        return_img(size)
      end
        return_img(size)
    }
  }
  location @invalid {
      content_by_lua_block {
        ngx.status = ngx.HTTP_BAD_REQUEST
      }
  }

Exampel url:

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

PreviousNGINX+Lua=parser_ipNextMong0

Last updated 5 years ago