echo-nginx-module是一個第三方模組,在nginx源碼中沒有,但是OpenResty中有,它為nginx.conf帶來了echo,sleep,time等多個類似bash的強大命令。
目前最新版本是v0.61
安裝指南參見
https://github.com/openresty/echo-nginx-module#installation
配置
server { listen 8081; server_name localhost; location /test { set $foo hello; echo "foo: $foo"; } location /test1 { set $first "hello "; echo "${first}world"; } location /foo { echo "foo = [$foo]"; } location /bar { set $foo 32; echo "bar = [$foo]"; } }
完整的nginx.conf如下:
https://github.com/taoyunxing/github_test/blob/master/nginx.conf
下載源碼
cd /usr/local/src
git clone https://github.com/openresty/echo-nginx-module.git
cd nginx-1.12.2
./configure --with-http_ssl_module \
--with-pcre=/usr/local/src/pcre-8.41 \
--with-zlib=/usr/local/src/zlib-1.2.11 \
--with-openssl=/usr/local/src/openssl-1.1.0g \
--with-http_stub_status_module \
--add-module=/usr/local/src/ngx_cache_purge \
--add-module=/usr/local/src/ngx_req_status \
--add-module=/usr/local/src/echo-nginx-module
make
make install
這個例子也給出了OpenResty中的模組如何編譯進社區最新版nginx中去的方法。我起初看到OpenResty中的模組目錄比較怪異,以為還需要自己調整目錄結構再整合到nginx中,其實是沒有必要的。
安裝完成之後,檢查nginx.conf的完整性並重啟nginx
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s stop
/usr/local/nginx/sbin/nginx
測試請求
curl -v 'http://localhost:8081/test'
curl -v 'http://localhost:8081/test1'
curl -v 'http://localhost:8081/foo'
curl -v 'http://localhost:8081/bar'
特殊說明
上面僅是最基本的用法,還有很多進階的用法有待後續深入探索時再補充上來。
下面是做得補充。
server { listen 8082; server_name localhost; location /foo { set $a hello; echo_exec /bar; } location /foo1 { set $a hello; rewrite ^ /bar; } location /bar { echo "a = [$a]"; } }
更新nginx.conf之後,執行下面的命令檢查
curl -v 'http://localhost:8082/foo'
curl -v 'http://localhost:8082/foo1'
下面是更進一步的例子
因為對內建變數 $args 的修改會直接導致當前請求的 URL 參數串發生變化,因此內建變數 $arg_XXX 自然也會隨之變化。
location /test3 { set $orig_a $arg_a; set $args "a=5"; echo "original a: $orig_a"; echo "a: $arg_a"; }
curl 'http://localhost:8082/test3?a=3'
server { listen 8083; server_name localhost; location /test { set $args "foo=1&bar=2"; proxy_pass http://127.0.0.1:8084/args; } } server { listen 8084; server_name localhost; location /args { echo "args: $args"; } }
curl -v 'http://localhost:8083/test?blah=7'
父子請求之間的變數共用
location /main { echo_location /foo2; echo_location /bar2; } location /foo2 { echo foo2; } location /bar2 { echo bar2; }
curl 'http://localhost:8082/main'
location /main3 { set $var main; echo_location /foo3; echo_location /bar3; echo "main: $var"; } location /foo3 { set $var foo; echo "foo: $var"; } location /bar3 { set $var bar; echo "bar: $var"; }
curl -v 'http://localhost:8082/main3'
參考文獻
[1].https://github.com/openresty/echo-nginx-module
[2].http://blog.sina.com.cn/s/blog_6d579ff40100wi7p.html