在配置和調試nginx.conf中的location時,有一個非常有用的模塊可以安裝,
那就是echo-nginx-module,它可以在location中直接使用類似linux shell命令echo一樣的指令,幫助驗證location配置是否符合預期。我在配置location的過程中,就遇到過奇怪的問題,最後發現因爲代碼走錯了location。
下載nginx源碼
mkdir nginx_1_12_1 git clone https://github.com/nginx/nginx/tree/branches/stable-1.12
使用默認選項配置,編譯,安裝nginx
./configure sudo make sudo make install
一切正常的話,會在/usr/local/nginx目錄下安裝好nginx.
使用下面命令啓動nginx.cd /usr/local/nginx/sbin ./nginx
如果啓動正常的話,可以查看到nginx啓動了兩個進程,master和worker進程。
root@rex-VirtualBox:/usr/local/nginx/sbin# ps ax|grep "nginx" 6347 ? Ss 0:00 nginx: master process ./nginx 6498 ? S 0:00 nginx: worker process 6803 pts/2 S+ 0:00 grep --color=auto nginx
打開瀏覽器,輸入
127.0.0.1
,可以看到nginx的歡迎頁面。下載echo-nginx-module模塊,這裏我把它作爲我nginx倉庫的一個子模塊來管理。
cd nginx_1_12_1 git submodule add git@github.com:openresty/echo-nginx-module.git
重新配置nginx,把echo-nginx-module模塊編譯進nginx可執行文件
sudo ./configure --add-module=echo-nginx-module sudo make sudo make install
修改/usr/local/nginx/conf/nginx.conf, 在server塊中增加下面語句
location /hello { echo -n "hello, "; echo "world!"; } location /timed_hello { echo_reset_timer; echo_sleep 1.4; echo hello world; echo "'hello world' takes about $echo_timer_elapsed sec."; echo_reset_timer; echo hiya igor; echo "'hiya igor' takes about $echo_timer_elapsed sec."; }
重新加載nginx的配置運行
cd /usr/local/nginx/sbin nginx -s reload
測試echo-nginx-module
rex@rex-VirtualBox:~/work/nginx_1_12_1$ curl http://127.0.0.1/hello hello, world! rex@rex-VirtualBox:~/work/nginx_1_12_1$ curl http://127.0.0.1/timed_hello hello world 'hello world' takes about 1.402 sec. hiya igor 'hiya igor' takes about 0.000 sec.
從這個簡單的demo中,就有兩個echo-nginx-module的使用場景,
- 使用echo指令,可以直觀地查看到調用不同的URL及對應的location
- 可以利用echo_reset_timer指令和變量echo_timer_elapsed,方便地進行計時,這樣就可以對某些命令對執行時間進行衡量。
當然,我相信echo-nginx-module有更多的用途,具體執行的說明可以參考官方網站。