Nginx擴展第三方模塊——echo
第三方模塊是對nginx的功能擴展,第三方模塊需要在編譯nginx的時候使用參數--add-module=PATH指定擴展模塊的源碼包路徑
給Nginx擴展添加echo功能,echo模塊的下載地址:
https://github.com/openresty/echo-nginx-module
[root@app src]# yum install git -y [root@app src]# git clone https://github.com/openresty/echo-nginx-module.git #把echo模塊從github上克隆下來 [root@app src]# nginx -s stop #擴展nginx的功能需要從新編譯,編譯前必須停止服務;如果服務不停止,則無法用新生成的nginx二級制程序替代原有程序 [root@app nginx-1.16.1]# ./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --with-file-aio --add-module=/usr/local/src/echo-nginx-module #添加模塊源碼路徑 [root@app nginx-1.16.1]# make -j 4 && make install [root@app nginx-1.16.1]# nginx location /echo { echo "hello world"; default_type text/html; } 當訪問www.xxx.com/echo時,將會在瀏覽器上打印"hello world" 如果不加default_type text/html;,訪問www.xxx.com/echo時,將會把它當做文件下載下來,因為echo默認不是mime里所支持的格式;加上這項是告訴瀏覽器用html的格式去解析它
echo模塊的應用
location /main { default_type text/html; echo "hello world,main-->" echo_reset_timer; echo_location /sub1; echo_location /sub2; echo "took $echo_timer_elapsed sec for total."; } location /sub1 { echo_sleep 1; echo sub1; } location /sub2 { echo_sleep 1; echo sub2; } echo模塊可以使用echo_location調用其他的location
Nginx常用內置變量
$remote_addr; #存放了客戶端的地址,注意是客戶端的公網IP,也就是一家人訪問一個網站,則會顯示為路由器的公網IP。 $args; #變量中存放了URL中的指令,例如http://www.magedu.net/main/index.do?id=20190221&partner=search中的id=20190221&partner=search;需要輸入指令 時,要添加?進行隔開,兩個指令中間需要用&進行隔開,args變量里面存放了id=20190221&partner=search $document_root; #所請求資源的location下面root所指定的路徑,如/apps/nginx/html。 $document_uri; #保存了當前請求中不包含指令的URI,注意是不包含請求的指令,比如http://www.magedu.net/main/index.do?id=20190221&partner=search會被定義為/main/index.do $host; #存放了請求的域名。 $http_user_agent; #客戶端瀏覽器的詳細信息。 $http_cookie; #客戶端的cookie信息。用戶登錄后才可以看到cookie信息。 $remote_port; #客戶端請求Nginx服務器時隨機打開的端口,這是每個客戶端自己的端口。 $remote_user; #已經經過Auth Basic Module驗證的用戶名。 $request_body_file; #做反向代理時發給后端服務器的本地資源的名稱。做反向代理時必須開啟。 $request_method; #請求資源的方式,GET/PUT/DELETE等。 $request_filename; #當前請求的資源文件的路徑名稱,由root或alias指令與URI請求生成的文件絕對路徑,如/apps/nginx/html/main/index.html $request_uri; #包含請求參數的原始URI,不包含主機名,如:/main/index.do?id=20190221&partner=search,打印整個uri。 $scheme; #請求的協議,如ftp,https,http等。 $server_protocol; #保存了客戶端請求資源使用的協議的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等。 $server_addr; #保存了服務器的IP地址。 $server_name; #請求的服務器的主機名,server_name。 $server_port; #請求的服務器的端口號。
自定義變量
location /test { default_type text/html; set $name user1; #設置變量並且賦值 echo $name; set $filename $request_filename; #一個變量的值可以是讀取另一個變量的值 echo $filename; } set只可以設置在server、location、if中