nginx之echo模块与内置变量

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中

猜你喜欢

转载自www.cnblogs.com/dongzhanyi123/p/12081468.html