OpenResty学习中的几个小例子汇总,openresty汇总


1.测试lua或是LuaJIT的版本号
如果使用的是标准 Lua,访问 /lua-version 应当返回响应体 Lua 5.1
如果是 LuaJIT 则应当返回类似 LuaJIT 2.0.2 这样的输出。
不要使用标准lua,应当使用luajit, 后者的效率比前者高多了。
在nginx.conf中的server中添加一个location。
location = /test {
location = /lua-version { 
 content_by_lua ' 
         if jit then 
                 ngx.say(jit.version) 
             else 
                 ngx.say(_VERSION) 
         end 
        '; 
}

使用下面的命令检验
curl -v 'http://localhost:20000/lua-version'


也可以直接用ldd命令验证是否链了libluajit-5.1这样的.so文件,例如

ldd /opt/openresty/nginx/sbin/nginx | grep --color lua


2.输出Hello World示例
在nginx.conf中的server中添加一个location。
location = /test {
       content_by_lua '
           ngx.say("Hello World")
           ngx.log(ngx.ERR, "err err err")
       ';
}
用户访问http://localhost:20000/test将会打印出“Hello World”内容。
curl -v http://localhost:20000/test


ngx.say是lua显露給模块的接口。
类似的有ngx.log(ngx.DEBUG, “”),可以在error.log输出调试信息。

另外也可以调用外部脚本,如同我们写php、jsp应用时,业务脚本单独组织在.php或.jsp文件中一样
location = /test2 {
       content_by_lua_file conf/lua/hello.lua;
}
文件hello.lua内容如下:
ngx.say("Hello World")
这里的脚本可以任意复杂,也可以使用Lua自己的库

刷新一下nginx.conf的配置
nginx -p ~/or_test -t
nginx -p ~/or_test -s reload

执行下面的命令
curl -v http://localhost:20000/test2

3.阻止某些用户代理访问网站
在nginx.conf中的server块中添加
if ($http_user_agent ~* (Wget|ab) ) {
   return 403;
}
来限制用户代理为wget和ab的请求访问
重新更新配置
nginx -p ~/or_test -t
nginx -p ~/or_test -s reload


请对比下面的3个请求
curl -v --user-agent wget http://localhost:20000/test2


curl -v --user-agent ab http://localhost:20000/test2

curl -v http://localhost:20000/test2



4.下面是整个nginx.conf的内容

worker_processes  1;
user root;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 20000;

        #deny some user-agents access
        if ($http_user_agent ~* (wget|ab)) {
            return 403;
        }

        location = /lua-version {
            content_by_lua '
                if jit then
                    ngx.say(jit.version)
                else
                    ngx.say(_VERSION)
                end
            ';
        }

        location = /test {
               content_by_lua '
                   ngx.say("Hello World")
                   ngx.log(ngx.ERR, "err err err")
               ';
        }

        location = /test2 {
               content_by_lua_file conf/lua/hello.lua;
        }

        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>hello, world</p>")
            ';
        }
    }
}


5.参考文献

[1].http://www.ttlsa.com/nginx/nginx-lua/

[2].http://www.ttlsa.com/nginx/how-to-nginx-block-user-agent/

相关内容

    暂无相关文章