NginxをLua拡張して簡単な短縮URLサービスを作った

Nginx Lua

準備

サーバOSはUbuntu15.10

% cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=15.10
DISTRIB_CODENAME=wily
DISTRIB_DESCRIPTION="Ubuntu 15.10"

Lua拡張を使いたいのでOpenRestyを導入する.

% sudo apt-get install libpcre3 libpcre3-dev
% sudo wget https://openresty.org/download/ngx_openresty-1.9.7.2.tar.gz
% sudo ./configure --prefix=/opt/openresty/1.9.7.2/

短縮URL記憶用にRedisを使ってみる.

% sudo apt-get install redis-server

nginx/conf/nginx.conf

worker_processes 4;

events {
        worker_connections 1024;
}

http {
        include mime.types;
        default_type application/octet-stream;
        sendfile on;
        keepalive_timeout 65;
        include /opt/openresty/1.9.7.2/nginx/conf/sites-enabled/*.conf;
}

nginx/conf/sites-enabled/200_shorten-url.conf

server {
        server_name 10.0.10.101;
        listen 90;
        default_type text/html;

        set $luad "/opt/openresty/1.9.7.2/nginx/conf/lua.d";

        rewrite_by_lua_file $luad/200_rewrite-shorten-url.lua;

        location /encode {
                content_by_lua_file $luad/201_encode-shorten-url.lua;
        }

        location /decode {
                content_by_lua_file $luad/202_decode-shorten-url.lua;
        }

        server_tokens off;
}

nginx/conf/lua.d/200_rewrite-shorten-url.lua

nginx/conf/lua.d/201_encode-shorten-url.lua

nginx/conf/lua.d/202_decode-shorten-url.lua

参考

Scripting Nginx with Lua
GitHub - openresty/lua-nginx-module
Nginx.org - Module ngx_http_core_module