安裝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) '; }
強制搜索引擎只索引mixlr.com
Google把子域名當作完全獨立的網站,我們不希望爬蟲抓取子域名的頁面,降低我們的Page rank。
1
2
3
4
5
6
7
|
location /robots.txt {
rewrite_by_lua '
if ngx.var.http_host ~= "mixlr.com" then
return ngx.exec("/robots_disallow.txt");
end
';
}
|
如果對robots.txt的請求不是mixlr.com域名的話,則內部重寫到robots_diallow.txt,雖然標准的重寫指令也可以實現這個需求,但是 Lua的實現更容易理解和維護。
根據程序邏輯設置響應頭
Lua提供了比Nginx默認配置規則更加靈活的設置方式。 在下面的例子中,我們要保證正確設置響應頭,這樣瀏覽器如果發送了指定請求頭后,就可以 無限期緩存靜態文件,是的用戶只需下載一次即可。
這個重寫規則使得任何靜態文件,如果請求參數中包含時間戳值,那么就設置相應的Expires和Cache-Control響應頭。
1
2
3
4
5
6
7
8
9
|
location / {
header_filter_by_lua '
if ngx.var.query_string and ngx.re.match( ngx.var.query_string, "^([0-9]{10})$" ) then
ngx.header["Expires"] = ngx.http_time( ngx.time() + 31536000 );
ngx.header["Cache-Control"] = "max-age=31536000";
end
';
try_files $uri @dynamic;}
|
刪除jQuery JSONP請求的時間戳參數
很多外部客戶端請求JSONP接口時,都會包含一個時間戳類似的參數,從而導致Nginx proxy緩存無法命中(因為無法忽略指定的HTTP參數)。下面的 規則刪除了時間戳參數,使得Nginx可以緩存upstream server的響應內容,減輕后端服務器的負載。
1
2
3
4
5
6
7
8
9
10
|
location / {
rewrite_by_lua '
if ngx.var.args ~= nil then
-- /some_request?_=1346491660 becomes /some_request
local fixed_args, count = ngx.re.sub( ngx.var.args, "&?_=[0-9]+", "" );
if count > 0 then
return ngx.exec(ngx.var.uri, fixed_args);
end
end
';}
|
把后端的慢請求日志記錄到Nginx的錯誤日志
如果后端請求響應很慢,可以把它記錄到Nginx的錯誤日志,以備后續追查。
1
2
3
4
5
6
|
location / {
log_by_lua '
if tonumber(ngx.var.upstream_response_time) >= 1 then
ngx.log(ngx.WARN, "[SLOW] Ngx upstream response time: " .. ngx.var.upstream_response_time .. "s from " .. ngx.var.upstream_addr);
end
';}
|
基於Redis的實時IP封禁
某些情況下,需要阻止流氓爬蟲的抓取,這可以通過專門的封禁設備去做,但是通過Lua,也可以實現簡單版本的封禁。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
lua_shared_dict banned_ips 1m;
location / {
access_by_lua '
local banned_ips = ngx.shared.banned_ips;
local updated_at = banned_ips:get("updated_at");
-- only update banned_ips from Redis once every ten seconds:
if updated_at == nil or updated_at < ( ngx.now() - 10 ) then
local redis = require "resty.redis";
local red = redis:new();
red:set_timeout(200);
local ok, err = red:connect("your-redis-hostname", 6379);
if not ok then
ngx.log(ngx.WARN, "Redis connection error retrieving banned_ips: " .. err);
else
local updated_banned_ips, err = red:smembers("banned_ips");
if err then
ngx.log(ngx.WARN, "Redis read error retrieving banned_ips: " .. err);
else
-- replace the locally stored banned_ips with the updated values:
banned_ips:flush_all();
for index, banned_ip in ipairs(updated_banned_ips) do
banned_ips:set(banned_ip, true);
end
banned_ips:set("updated_at", ngx.now());
end
end
end
if banned_ips:get(ngx.var.remote_addr) then
ngx.log(ngx.WARN, "Banned IP detected and refused access: " .. ngx.var.remote_addr);
return ngx.exit(ngx.HTTP_FORBIDDEN);
end
';}
|
現在就可以阻止特定IP的訪問:
1
|
ruby> $redis.sadd("banned_ips", "200.1.35.4")
|
Nginx進程每隔10秒從Redis獲取一次最新的禁止IP名單。需要注意的是,如果架構中使用了Haproxy這樣類似的負載均衡服務器時, 需要把$remote_addr設置為正確的遠端IP地址。
這個方法還可以用於HTTP User-Agent字段的檢查,要求滿足指定條件。
使用Nginx輸出CSRF(form_authenticity_token)
Mixlr大量使用頁面緩存,由此引入的一個問題是如何給每個頁面輸出會話級別的CSRF token。我們通過Nginx的子請求,從upstream web server 獲取token,然后利用Nginx的SSI(server-side include)功能輸出到頁面中。這樣既解決了CSRF攻擊問題,也保證了cache能被正常利用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
location /csrf_token_endpoint {
internal;
include /opt/nginx/conf/proxy.conf;
proxy_pass "http://upstream";}
location @dynamic {
ssi on;
set $csrf_token '';
rewrite_by_lua '
-- Using a subrequest, we our upstream servers for the CSRF token for this session:
local csrf_capture = ngx.location.capture("/csrf_token_endpoint");
if csrf_capture.status == 200 then
ngx.var.csrf_token = csrf_capture.body;
-- if this is a new session, ensure it sticks by passing through the new session_id
-- to both the subsequent upstream request, and the response:
if not ngx.var.cookie_session then
local match = ngx.re.match(csrf_capture.header["Set-Cookie"], "session=([a-zA-Z0-9_+=/+]+);");
if match then
ngx.req.set_header("Cookie", "session=" .. match[1]);
ngx.header["Set-Cookie"] = csrf_capture.header["Set-Cookie"];
end
end
else
ngx.log(ngx.WARN, "No CSRF token returned from upstream, ignoring.");
end
';
try_files /maintenance.html /rails_cache$uri @thin;}
|
CSRF token生成 app/metal/csrf_token_endpoint.rb:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class CsrfTokenEndpoint
def self.call(env)
if env["PATH_INFO"] =~ /^\/csrf_token_endpoint/
session = env["rack.session"] || {}
token = session[:_csrf_token]
if token.nil?
token = SecureRandom.base64(32)
session[:_csrf_token] = token
end
[ 200, { "Content-Type" => "text/plain" }, [ token ] ]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
endend
|