安裝lua_nginx_module 模塊
lua_nginx_module 可以一步步的安裝,也可以直接用淘寶的OpenResty
Centos和debian的安裝就簡單了。。
這里說下freebsd的安裝:
fetch http://www.lua.org/ftp/lua-5.1.4.tar.gz tar zxvf lua-5.1.4.tar.gz cd lua-5.1.4 make freebsd make install cd .. fetch https://github.com/chaoslawful/lua-nginx-module/zipball/v0.1.6rc2 fetch https://github.com/simpl/ngx_devel_kit/zipball/v0.2.17rc2 tar zxvf v0.1.6rc2 mv chaoslawful-lua-nginx-module-ccaf132 lua_nginx_module tar zxvf v0.2.17rc2 mv simpl-ngx_devel_kit-bc97eea ngx_devel_kit tar zxvf pcre-8.12.tar.gz tar zxvf nginx-1.0.3.tar.gz cd nginx-1.0.3 ./configure --prefix=/data/soft/nginx --with-pcre=../pcre-8.12 --add-module=../ngx_devel_kit --add-module=../lua_nginx_module make && make install
安裝完成后,我們體驗一下lua
第一個lua腳本
ngx.say 是打印的打印輸出的意思。。。
location /echo { default_type text/plain; echo hello lua; } location /lua { default_type text/plain; content_by_lua 'ngx.say("hello world")'; }
用lua腳本做nginx的訪問的限制...
location @client{ proxy_pass http://www.ruifengyun.com; } location ~ /test { default_type text/html; content_by_lua 'ngx.say("this is ruifengyun.com!")'; access_by_lua ' if ngx.var.remote_addr == "10.2.20.110" then ngx.exit(ngx.HTTP_FORBIDDEN) end if ngx.var.remote_addr == "10.2.20.112" then ngx.exec("@client") end '; }
控制經過判斷之后,才能訪問
location / { access_by_lua ' local res = ngx.location.capture("/auth") if res.status == ngx.HTTP_OK then return end if res.status == ngx.HTTP_FORBIDDEN then ngx.exit(res.status) end ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) '; # proxy_pass/fastcgi_pass/postgres_pass/... }
使用lua做nginx的rewrite跳轉
這個是先判斷 check-pam接口的return的內容是不是spam,是的話,轉跳到其他的頁面
location / { rewrite_by_lua ' local res = ngx.location.capture("/check-spam") if res.body == "spam" then ngx.redirect("/terms-of-use.html") end '; fastcgi_pass ...; }
根據ip做不同的響應
location / { content_by_lua ' myIP = ngx.req.get_headers()["X-Real-IP"] if myIP == nil then myIP = ngx.req.get_headers()["x_forwarded_for"] end if myIP == nil then myIP = ngx.var.remote_addr end if myIP == "" then ngx.exec("@client") else ngx.exec("@client_test") end '; }
redirect的使用
return ngx.redirect("/foo") return ngx.redirect("http://localhost:1984/foo", ngx.HTTP_MOVED_TEMPORARILY) return ngx.redirect("/foo", 301)
返回302臨時重定向 地址欄會顯示跳轉后的地址
rewrite ^ /foo? redirect; # nginx config return ngx.redirect('/foo'); -- lua code
lua過濾post過來的參數
location = /test { content_by_lua ' ngx.req.read_body() local args = ngx.req.get_post_args() for key, val in pairs(args) do if type(val) == "table" then ngx.say(key, ": ", table.concat(val, ", ")) else ngx.say(key, ": ", val) end end '; }
一個Lua的例子:
#!/usr/bin/env lua ngx.say('aaaaaa </br>') local url = ngx.var.uri ngx.say('<br>',url,'<br/>') ngx.print('這次訪問的header頭是 ',ngx.req.raw_header()) ngx.print('<meta http-equiv="content-type" content="text/html;charset=utf-8">') ngx.print('<h1> 這個是 h1 </h1>') ngx.print('這次訪問的是 get 還是 post 呀 ',ngx.req.get_Method()) local args = ngx.req.get_uri_args() ngx.print(args) local res = ngx.location.capture("/") ngx.print('<br>http code <br>‘,res.status)
lua 調用mysql的例子
worker_processes 2; error_log logs/error.log warn; events { worker_connections 1024; } http { upstream backend { drizzle_server 127.0.0.1:3306 protocol=mysql dbname=ngx_test user=ngx_test password=ngx_test; drizzle_keepalive max=10 overflow=ignore mode=single; } server { listen 8080; location @cats-by-name { set_unescape_uri $name $arg_name; set_quote_sql_str $name; drizzle_query 'select * from cats where name=$name'; drizzle_pass backend; rds_json on; } location @cats-by-id { set_quote_sql_str $id $arg_id; drizzle_query 'select * from cats where id=$id'; drizzle_pass backend; rds_json on; } location = /cats { access_by_lua ' if ngx.var.arg_name then return ngx.exec("@cats-by-name") end if ngx.var.arg_id then return ngx.exec("@cats-by-id") end '; rds_json_ret 400 "expecting \"name\" or \"id\" query arguments"; } } }
改改密碼就能用啦~
lua獲取url中的參數
location = /adder { set_by_lua $res " local a = tonumber(ngx.arg[1]) local b = tonumber(ngx.arg[2]) return a + b" $arg_a $arg_b; echo $res; }
ngx.req.set_uri
nginx里面的配置是:
location /test { rewrite ^/test/(.*) /$1 break; proxy_pass http://my_backend; }
lua里面的配置是:
location /test { rewrite_by_lua ' local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "$1", "o") ngx.req.set_uri(uri) '; proxy_pass http://my_backend; }
我想大家看這個對照,已經知道是啥意思了.
通過lua獲取nginx的內置變量,通過這些變量做些邏輯的處理~
Nginx提供了很多內置的變量,如:
- $arg_PARAMETER 這個變量包含在查詢字符串時GET請求PARAMETER的值。
- $args 這個變量等於請求行中的參數。
- $binary_remote_addr 二進制碼形式的客戶端地址。
- $body_bytes_sent 傳送頁面的字節數
- $content_length 請求頭中的Content-length字段。
- $content_type 請求頭中的Content-Type字段。
- $cookie_COOKIE cookie COOKIE的值。
- $document_root 當前請求在root指令中指定的值。
- $document_uri 與$uri相同。
- $host 請求中的主機頭字段,如果請求中的主機頭不可用,則為服務器處理請求的服務器名稱。
- $is_args 如果$args設置,值為"?",否則為""。
- $limit_rate 這個變量可以限制連接速率。
- $nginx_version 當前運行的nginx版本號。
- $query_string 與$args相同。
- $remote_addr 客戶端的IP地址。
- $remote_port 客戶端的端口。
- $remote_user 已經經過Auth Basic Module驗證的用戶名。
- $request_filename 當前連接請求的文件路徑,由root或alias指令與URI請求生成。
- $request_body 這個變量(0.7.58+)包含請求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比較有意義。
- $request_body_file 客戶端請求主體信息的臨時文件名。
- $request_completion 未知。
- $request_method 這個變量是客戶端請求的動作,通常為GET或POST。包括0.8.20及之前的版本中,這個變量總為main request中的動作,如果當前請求是一個子請求,並不使用這個當前請求的動作。
- $request_uri 這個變量等於包含一些客戶端請求參數的原始URI,它無法修改,請查看$uri更改或重寫URI。
- $scheme 所用的協議,比如http或者是https,比如rewrite ^(.+)$ $scheme://example.com$1 redirect;
- $server_addr 服務器地址,在完成一次系統調用后可以確定這個值,如果要繞開系統調用,則必須在listen中指定地址並且使用bind參數。
- $server_name 服務器名稱。
- $server_port 請求到達服務器的端口號。
- $server_protocol 請求使用的協議,通常是HTTP/1.0或HTTP/1.1。
- $uri 請求中的當前URI(不帶請求參數,參數位於$args),可以不同於瀏覽器傳遞的$request_uri的值,它可以通過內部重定向,或者使用index指令進行修改。
另外: HTTP_X_FORWARDED_FOR是透過代理服務器取得客戶端的真實IP地址,有些用此方法讀取到的仍然是代理服務器的IP。還有一點需要注意的是:如果客戶端沒有通過代理服務器來訪問,那么用 HTTP_X_FORWARDED_FOR 取到的值將是空的。
函數版的訪問
location /lua1 { default_type 'text/plain'; content_by_lua 'ngx.say("hello, lua")'; } # 請求另外的url location /lua2 { content_by_lua ' local res = ngx.location.capture("/hello1") ngx.say("data: " .. res.body) '; }