neverlock
12/1/2015 - 2:06 AM

Simple nginx config with lua script

Simple nginx config with lua script

-- lua/render.lua
local template = require "resty.template"
local data = {
    title = 'F5, Demo',
    message = "Hello, World!"
}

template.render([[
<!DOCTYPE html>
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    <h1>{{message}}</h1>
</body>
</html>
]], data)
-- lua/post.lua
local cjson = require 'cjson'
ngx.req.read_body()
local data = ngx.req.get_body_data()
if not data then
    ngx.say(cjson.encode({ error = 1, message = 'POST data not found' }))
    ngx.exit(ngx.HTTP_OK)
end

ngx.say("BODY DATA : " ..data)
local json = cjson.decode(data)

if not json.username then
    ngx.say(cjson.encode({ error = 1, message = 'Username not found' }))
end

ngx.say('Do signup.')
ngx.say('User info.')
ngx.say(cjson.encode(json))

error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    proxy_cache_path /data/cache/page levels=1:2 keys_zone=python:10m max_size=1g inactive=5m;
    server {
        access_log logs/access.log;
        listen 8080;
        lua_code_cache  off;

        location / {
            echo "Hello, World";
        }

        location ~ ^/api/v1/(.*)$ {
            # path to lua script
            content_by_lua_file lua/$1.lua;
        }

        location /page/ {
            set $cache_key $scheme$host$uri$is_args$args;
            proxy_cache_key $cache_key;
            proxy_cache_valid 30m;
            proxy_cache python;
            proxy_pass http://127.0.0.1:8004/;
        }

    }
}