程序里helloworld
1. 最简单的hello world
location /hello {
echo "hello world!";
}
2. 异步请求其他echo请求
location /hellotwo {
echo "hello world?";
echo_location_async /hello;
}
3. 输出GET请求参数,假设参数名是name,这里并对name参数进行解码
location /hellothree {
set_unescape_uri $name $arg_name;
set_if_empty $name "None";
echo "hello, $name!";
}
例2中的subrequest是完全non-blocking的。
echo模块还有timer扩展,页面输出加载时间也是小case了。
Memcached HTTP 接口
location /memcached {
set $memc_cmd $arg_cmd;
set $memc_key $arg_key;
set $memc_value $arg_val;
set $memc_exptime $arg_exptime;
memc_pass 127.0.0.1:11211;
}
URL访问类似 http://host:port/memcached?cmd=aaa&key=bbb&val=ccc
数据库查询
# 添加MySQL配置
upstream mysql {
drizzle_server 10.8.9.30:3306 dbname=home user=uchome password=uchome protocol=mysql;
}
# 通过url匹配出name,并编码防止注入,最后以json格式输出结果。
location ~ '^/mysql/(.*)' {
set $name $1;
set_quote_sql_str $quote_name $name;
set $sql "SELECT * FROM users WHERE name=$quote_name";
drizzle_query $sql;
drizzle_pass mysql;
rds_json on;
}
# 查看MySQL服务状态,这个很实用哦。
location /mysql-status {
drizzle_status;
}
lua扩展
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)
';
}
Lua支持的选项很多,具体可参考官网WIKI文档。http://wiki.nginx.org/HttpLuaModule