D
D
Dmitry Sergeev2019-06-10 12:32:06
Nginx
Dmitry Sergeev, 2019-06-10 12:32:06

How to use nginx to give a stub image and call a lua script?

That is, to do image proxying with the following algorithm of actions:
1. Image request
2. Nginx checks whether the requested image exists on the server
3. If yes, we give it away,
4. If not, then we give a stub image with caching, say, at 10 minutes and call a lua script that downloads a picture from a certain site, conjures over it and puts it in a directory in order to give it back in 10 minutes.
For now, I'm just trying to achieve at least that the stub is given and the lua script is called, something like this:
nginx config

......
       location / {
                # Проверим есть ли файл и если да - отдадим его
                # если нет, вызовем @lua_call
                try_files $uri @lua_call;
        }

        location @lua_call {
            #rewrite ^ /default.jpg;  - если убрать коммент не будет вызова луа-скрипта ниже
            rewrite_by_lua_file /var/www/site/www/images/hello.lua;
            # Отключим кэширование кода для разработки
            lua_code_cache off;
        }

The hello.lua script works, but it's embarrassing that the output of the stub comes at the end of the script, after the "hardcore"
hello.lua (for now, just create a text file in order to make sure that the script is called)
local file = io.open("/var/www/site/www/images/test.txt", "w");
file:write("Hello World");
file:close();
return ngx.exec('/default.jpg');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Sergeev, 2019-06-10
@JetMaster

everything turned out to be just
location @lua_call {
rewrite ^ /default.jpg break;
rewrite_by_lua_file /var/www/site/www/images/hello.lua;
# Disable code caching for development
lua_code_cache off;
}
read the doc https://github.com/openresty/lua-nginx-module#rewr...
This will be the case if rewrite ^ /bar last is used as this will similarly initiate an internal redirection. If the break modifier is used instead, there will be no internal redirection and the rewrite_by_lua code will be executed.

R
Randewoo, 2019-12-04
@Randewoo

ngx.say('<img src="/default.jpg">');
ngx.eof();

Well, as it were, yes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question