Nginx echo 模块是在 nginx 程序上扩展了 echo 输出字符的功能,对于调试很方便,项目地址: https://github.com/openresty/echo-nginx-module 。
安装
目前支持
nginx-1.11.2,高版本可能安装失败,我装1.11.13失败了,更多支持 nginx 的版本见: https://github.com/openresty/echo-nginx-module#compatibility
去 release 下载最新的安装包,并解压.
在配置 Nginx 时用: ./configure --add-module=/你的解压路径,并编译安装,如果是重新编译安装可参考: 重新编译安装
使用
只是研究了一些常用的
echo - 输出字符
- 语法:
echo [options] <string>... 默认值:
no# 简单的hello,world!server {location = /api/hello {echo "hello,world!";}}
默认 echo 会自动换行,不需要换行可以:
echo -n xxx;;echo_before_body,echo_after_body - 页面前、后插入内容
语法:
echo_before_body [options] [argument]...默认值:
noserver {# 简单的输出location = /api/hello {echo_before_body echo_before_body;echo "hello,world!";echo_after_body echo_after_body;}# 常见于代理页面前、后插内容location = /api/proxy_before_after {echo_before_body echo_before_body;echo_before_body echo_before_body;proxy_pass http://127.0.0.1;echo_after_body echo_after_body;echo_after_body echo_after_body;}}
echo_sleep - 请求等待
语法:
echo_sleep <seconds>默认值:
noserver {# 简单的输出location = /api/sleep {echo 1;# 等待1秒echo_sleep 1;echo 2;}}
echo_location_async,echo_location - 请求指定路径
语法:
echo_location_async <location> [<url_args>]- 默认值:
no
异步跟同步的区别是:location /main {# 异步调用/subecho_location_async /sub;echo world;}location /main2 {# 同步调用/subecho_location_async /sub;echo world;}location /sub {echo hello;}
- 异步会并行的去请求
- 同步等待当前请求结束才会往下执行
下面这个整个时间为 2s,因为新路径最大是 2s:
location /main {echo_location_async /sub1;echo_location_async /sub2;echo "took $echo_timer_elapsed sec for total.";}location /sub1 {echo_sleep 2;}location /sub2 {echo_sleep 1;}
下面这个整个时间为 3s,因为需要等待/sub1完成才进入/sub2:
location /main {echo_location /sub1;echo_location /sub2;echo "took $echo_timer_elapsed sec for total.";}location /sub1 {echo_sleep 2;}location /sub2 {echo_sleep 1;}
可以通过第二个参数传querystring: echo_location_async /sub 'foo=Foo&bar=Bar';
echo_foreach_split - 分隔循环
语法:
echo_foreach_split <delimiter> <string>location /split {echo_foreach_split ',' $arg_list;echo "item: $echo_it";echo_end;}
上面配置当访问:
/split?list=cat,dog,mouse时会输出:item: catitem: dogitem: mouse
$arg_list是对应$args.list
那么配置全echo_location_async可以做成nginx-combo服务了,如:location = /api/combo {echo_foreach_split ',' $query_string;echo "/* combo: $echo_it */";echo_location_async $echo_it;echo;echo_end;}
访问:
/api/combo?/a.js,/b.js,需要注意的是文件的路径必须以/开始,因为匹配的location,当然真的nginx-combo服务请看: nginx-http-concat
其他变量请去官网查看~link
- 我写的在线 Demo
