nginx以及openresty

一 Nginx的简介

1.1 简介

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点开发的,第一个公开版本0.1.0发布于2004年10月4日。

因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

其他特点:运行稳定,开源,免费。

1.2 Nginx的应用场景

-1. 作为http服务器
-2. 充当虚拟主机
-3. 反向代理
-4. 负载均衡

二 Nginx的安装

2.1 上传、解压、更名

[root@qianfeng01 ~]# tar -zxvf nginx-1.8.0.tar.gz -C /usr/local

2.2 环境准备

1) 安装c语言环境

因为nginx的编译需要c语言环境

[root@qianfeng01 ~]# yum -y install gcc-c++

2)安装插件pcre和pcre-devel

[root@qianfeng01 ~]# yum install -y pcre pcre-devel

3)安装压缩工具zlib和zlib-devel

[root@qianfeng01 ~]# yum install -y zlib zlib-devel

4)安装支持https协议的相关工具

这两款工具,要安装上openssl和openssl-devel

[root@qianfeng01 ~]# yum install -y openssl openssl-devel

2.3 指定nginx的配置路径,并执行配置

[root@qianfeng01 ~]#  mkdir /usr/local/nginx/tmp
[root@qianfeng01 ~]#  cd /usr/local/nginx
[root@qianfeng01 nginx]# ./configure \
    --prefix=/usr/local/nginx \
    --pid-path=/usr/local/nginx/tmp/nginx.pid \
    --lock-path=/usr/local/nginx/tmp/nginx.lock \
    --error-log-path=/usr/local/nginx/tmp/error.log \
    --http-log-path=/usr/local/nginx/tmp/access.log \
    --with-http_gzip_static_module \
    --http-client-body-temp-path=/usr/local/nginx/tmp/client \
    --http-proxy-temp-path=/usr/local/nginx/tmp/proxy \
    --http-fastcgi-temp-path=/usr/local/nginx/tmp//fastcgi \
    --http-uwsgi-temp-path=/usr/local/nginx/tmp/uwsgi \
    --http-scgi-temp-path=/usr/local/nginx/tmp/scgi

2.4 执行安装

[root@qianfeng01 nginx]# make & make install

然后查看nginx目录下是否有sbin目录,如果有,证明安装成功。

2.5 常用参数的查看

[root@qianfeng01 nginx]# ./sbin/nginx -h
nginx version: nginx/1.8.0
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/local/nginx/)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file
# 启动nginx的进程命令
[root@qianfeng01 nginx]# ./sbin/nginx
#可以查看启动后的进程
[root@qianfeng01 nginx]# ps -ef | grep nginx

# 启动nginx的进程命令
[root@qianfeng01 nginx]# ./sbin/nginx -s stop
# 重新启动nginx的进程命令
[root@qianfeng01 nginx]# ./sbin/nginx -s reload

#查看nginx的其他选项
[root@qianfeng01 nginx]# ./sbin/nginx -h

**注意:**你可以配置环境变量了。

[root@qianfeng01 nginx]# vi /etc/profile
......省略....
# nginx  environment
export NGINX_HOME=/usr/local/nginx
export PATH=$NGINX_HOME/sbin:$PATH

三 Nginx的应用

3.1 默认配置文件的解析

文件:${NGINX_HOME}/conf/nginx.conf

#user  nobody;							/*  用户和用户组的配置    */
worker_processes  1;					/*  worker进程的数量    */

#error_log  logs/error.log;				/*  错误日志的位置信息和级别    */
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;				/*  进程id的文件的位置    */


events {
    worker_connections  1024;			/*  同时连接到nginx的最大连接数    */
}


http {
    include       mime.types;              
    default_type  application/octet-stream;
	
	/*  访问日志的格式,通常程序员会进行修改的。 main是日志格式的名称,后面是具体格式    */
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;    /*  使用日志格式的main规定的格式    */

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;				/*  监听端口    */
        server_name  localhost;			/*  监听的地址    */

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {			    /*  指定匹配规则    */
            root   html;				/*  指定根目录    */
            index  index.html index.htm;	/*  指定默认访问的文件    */
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

3.2 http服务

本身就是一个http服务器。使用默认的配置文件nginx.conf,默认端口是80,访问的根目录是html,默认首页是index.html

3.3 虚拟主机

就是nginx可以通过配置充当多个服务器

##步骤1:
[root@qianfeng01 html]# vi /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=none
NAME=ens33
DEVICE=ens33
ONBOOT=yes

IPADDR=192.168.10.101
IPADDR1=192.168.10.201			<===============追加一个ip地址


PREFIX=24
GATEWAY=192.168.10.2
DNS1=114.114.114.114
DNS2=8.8.8.8

[root@qianfeng01 html]# systemctl restart network
[root@qianfeng01 html]# ping 192.168.10.201


##步骤2: 修改nginx.conf配置文件,添加两个server,如下

server {
        listen       8089;					<===============配置端口号,也可使用默认的80
        server_name  192.168.10.101;
        #access_log tmp/access.log my_log;

        location / {
            root html;
            index  my1.html index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
server {
        listen       8089;
        server_name  192.168.10.201;
        location / {
            root html;
            index  my2.html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
##步骤3:在html下,创建一个my1.html 和 my2.html文件,修改其内容



##步骤4:重新加载nginx.conf配置文件
[root@qianfeng01 html]# nginx -c conf/nginx.conf -s reload

##步骤5:测试
在远程机器windows上使用浏览器访问192.168.10.101:8089 
和192.168.10.201:8089

3.4 反向代理

正向代理和反向代理的区别,如下图

在这里插入图片描述

第一步:在三台机器上安装tomcat

修改每个tomcat的首页信息:
首页位置:/usr/local/apache-tomcat-7.0.47/webapps/ROOT/index.jsp

第二步:启动tomcat

[root@qianfeng01 ~]# /usr/local/apache-tomcat-7.0.47/bin/startup.sh
[root@qianfeng02 ~]# /usr/local/apache-tomcat-7.0.47/bin/startup.sh
[root@qianfeng03 ~]# /usr/local/apache-tomcat-7.0.47/bin/startup.sh

第三步:配置nginx.conf文件

server {
        listen       80;
        server_name  www.baidu.com;			
        #access_log tmp/access.log my_log;

        location / {
            proxy_pass   http://tomcat1;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
server {
        listen       80;
        server_name  www.umeng.com;			
        #access_log tmp/access.log my_log;

        location / {
            proxy_pass   http://tomcat2;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}
server {
        listen       80;
        server_name  www.taobao.com;			
        #access_log tmp/access.log my_log;

        location / {
            proxy_pass   http://tomcat3;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
} 
upstream tomcat1 {
	server 192.168.10.101:8080;
}
upstream tomcat2 {
	server 192.168.10.102:8080;
}  
upstream tomcat3 {
	server 192.168.10.103:8080;
} 

第四步:重新加载nginx的配置文件

第五步:修改windows的hosts文件:C:\Windows\System32\drivers\etc

192.168.10.101 qianfeng01  www.baidu.com   www.umeng.com  www.taobao.com

第六步:清空浏览器的cookie记录

第七步:测试

在浏览器的地址栏上输入上面三个域名

3.5 负载均衡

负载均衡的配置信息

down : 表示当前的server暂时不参与负载
weight : 默认为1,weight越大表示负载的权重越大。
max_fails : 允许的请求失败的次数,默认为1,当超过最大次数的时候,返回proxy_next_upstream模块中定义的错误
fail_timeout_max_fails : 当出现max_fails次错误之后,暂定的时间
backup : 其他所有的非backup的机器down或者忙的时候,请求backup机器,所以这台机器一般压力都很轻
server {
        listen       80;
        server_name  www.baidu.com;			
        #access_log tmp/access.log my_log;

        location / {
            proxy_pass   http://tomcat1;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
upstream tomcat1 {
	server 192.168.10.101:8080 weight=5;
	server 192.168.10.102:8080;
	server 192.168.10.103:8080;
}

四 Nginx的其他内容

4.1 Nginx的变量

4.1.1)说明

Nginx中是支持变量的写法,可以自定义变量,也有内置的变量。
自定义变量时,需要使用set指令,变量需要使用$开头

测试变量的方式有两种,第一种是采集到日志文件中
第二种是使用echo指令,但是需要安装echo模块

4.1.2) Nginx内置的变量

$http_user_agent		#浏览器类型
$arg_name						#请求中的的参数名,即“?”后面的arg_name=arg_value形式的arg_name
$args								#请求中的参数值
$binary_remote_addr	#客户端地址的二进制形式, 固定长度为4个字节
$body_bytes_sent		#传输给客户端的字节数,响应头不计算在内
$bytes_sent					#传输给客户端的字节数
$connection					#TCP连接的序列号
$connection_requests #TCP连接当前的请求数量 
$content_length #“Content-Length” 请求头字段
$content_type #“Content-Type” 请求头字段
$cookie_name #cookie名称
$document_root #当前请求的文档根目录或别名
$document_uri #同 $uri
$host #优先级如下:HTTP请求行的主机名>”HOST”请求头字段>符合请求的服务器名
$hostname #主机名
$http_name #匹配任意请求头字段; 变量名中的后半部分“name”可以替换成任意请求头字段,如在配置文件中需要获取http请求头:“Accept-Language”,那么将“-”替换为下划线,大写字母替换为小写,形如:$http_accept_language即可。
$https #如果开启了SSL安全模式,值为“on”,否则为空字符串。
$is_args #如果请求中有参数,值为“?”,否则为空字符串。
$limit_rate #用于设置响应的速度限制,详见 limit_rate。
$msec #当前的Unix时间戳 
$nginx_version #nginx版本
$pid #工作进程的PID
$pipe #如果请求来自管道通信,值为“p”,否则为“.”
$proxy_protocol_addr #获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串。
$query_string #同 $args
$realpath_root #当前请求的文档根目录或别名的真实路径,会将所有符号连接转换为真实路径。
$remote_addr #客户端地址
$remote_port #客户端端口
$remote_user #用于HTTP基础认证服务的用户名
$request #代表客户端的请求地址
$request_body #客户端的请求主体
$request_body_file #将客户端请求主体保存在临时文件中
$request_completion #如果请求成功,值为”OK”,如果请求未完成或者请求不是一个范围请求的最后一部分,则为空。
$request_filename #当前连接请求的文件路径。
$request_length #请求的长度 (包括请求的地址, http请求头和请求主体)
$request_method #HTTP请求方法,通常为“GET”或“POST”
$request_time	#处理客户端请求使用的时间; 从读取客户端的第一个字节开始计时。
$request_uri #这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI,不包含主机名,例如:”/cnphp/test.php?arg=freemouse”。
$scheme #请求使用的Web协议, “http” 或 “https”
$sent_http_name #可以设置任意http响应头字段; 变量名中的后半部分“name”可以替换成任意响应头字段,如需要设置响应头Content-length,那么将“-”替换为下划线,大写字母替换为小写,形如:$sent_http_content_length 4096即可。
$server_addr #服务器端地址
$server_name #服务器名
$server_port #服务器端口
$server_protocol #服务器的HTTP版本, 通常为 “HTTP/1.0” 或 “HTTP/1.1”
$status #HTTP响应代码
$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space #客户端TCP连接的具体信息
$time_iso8601 #服务器时间的ISO 8610格式
$time_local #服务器时间(LOG Format 格式)
$uri #请求中的当前URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改,$uri不包含主机名,如”/foo/bar.html”。

4.1.3)安装echo模块

##下载echo模块包
wget https://github.com/openresty/echo-nginx-module/archive/v0.60.tar.gz
##解压
tar -zxvf v0.60.tar.gz -C /usr/local/nginx
##重新配置路径,包括echo模块
[root@qianfeng01 nginx]# ./configure \
    --prefix=/usr/local/nginx \
    --pid-path=/usr/local/nginx/tmp/nginx.pid \
    --lock-path=/usr/local/nginx/tmp/nginx.lock \
    --error-log-path=/usr/local/nginx/tmp/error.log \
    --http-log-path=/usr/local/nginx/tmp/access.log \
    --with-http_gzip_static_module \
    --http-client-body-temp-path=/usr/local/nginx/tmp/client \
    --http-proxy-temp-path=/usr/local/nginx/tmp/proxy \
    --http-fastcgi-temp-path=/usr/local/nginx/tmp//fastcgi \
    --http-uwsgi-temp-path=/usr/local/nginx/tmp/uwsgi \
    --http-scgi-temp-path=/usr/local/nginx/tmp/scgi \
    --add-module=/usr/local/nginx/echo-nginx-module-0.60
## 重新安装

[root@qianfeng01 nginx]# make && make install    

4.1.4)测试变量,打印到浏览器上

##1. 编写conf/my.conf
[root@qianfeng01 nginx]# vim conf/my.conf
events {
    worker_connections  1024;
}

http{
    server{
         listen 10086;
         server_name    localhost;
         location / {
             context "text/html"
             set $hobby "book";
             echo "$http_user_agent  $hobby 3:$remote_addr 4:$arg_passwd";
         }
    }
}
##2. 测试配置文件
[root@qianfeng01 nginx]# nginx -c conf/my.conf -t
nginx: the configuration file /usr/local/nginx/conf/my.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/my.conf test is successful
##3. 重新加载
[root@qianfeng01 nginx]# nginx -c conf/my.conf -s reload

##4. 在浏览器上输入以下地址:
192.168.10.101:10086/f1?passwd=123456

4.2 location的匹配规则

server里的location配置是用于匹配http协议的路径的,可以有以下匹配规则

#语法规则
location [=|~|~*|^~] /uri/ {}
#示例
location = /uri     # =开头表示精确匹配,只有完全匹配上才能生效。
location ~ pattern   # ~ 开头表示区分大小写的正则匹配。
location ~* pattern  # ~*开头表示不区分大小写的正则匹配。
location ^~ /uri     # ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location /uri      # 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后。
location /        # 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default。 

测试:

events {
    worker_connections  1024;
}

http{
    server{
         listen 10086;
         server_name    localhost;
         location ~ /abc {
         	 default_type  text/html;
             root html;
             index abc.html abcd.html;
         }
    }
}

浏览器访问:
http://qianfeng01:10086/abc.html
http://qianfeng01:10086/abcd.html

4.3 日志指令

Nginx的日志包含了两类:访问日志(access log)和错误日志(error log)。

访问日志相关指令主要有两条:

1)log_format,用来设置日志格式。

log_format name format
#name:指的是日志格式的名称(后面由access_log指令调用)
#format:设置日志具体格式

#示例
log_format onelog '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '"$request_time"';
#可以配置在http块中。

2)access_log,用来指定日志文件的存放路径、类型、缓存大小等。

access_log  /var/log/nginx/access.log  onelog;
#可以配置在http、server、location块中。

3)错误日志指令:error_log ,用来指定错误日志文件的存储路径以及日志级别

error_log logs/nginx_error.log error;		# 错误日志路径,和日志级别。
#常见的错误日志级别有debug | info | notice | warn | error | crit | alert | emerg
#可以配置在main、http、server、location块中。
#配置文件中定义了两个error_log,在同一个配置段里的话会产生冲突,所以同一个段里只允许配置一个error_log。但是,在不同的配置段中出现是没问题的。

error_log /dev/null;	#关闭error_log

4.4 进程processes说明

"master"进程负责管理"worker"进程,除了管理” worker"进程,"master"进程还负责读取配置文件、判断配置文件语法的工作,“master进程"也叫"主进程”

"worker"进程真正负责处理请求的进程。

在Nginx中,"master"进程只能有一个,而"worker"进程可以有多个,"worker"进程的数量可以自行定义。

worker_processes  1;

4.5 ngx_lua_modul模块的安装

##扩展阅读》》lua脚本语言介绍
--1. Lua是一个小巧的脚本语言。作者是巴西人。该语言的设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。
--2. Lua脚本可以很容易的被C/C++代码调用,也可以反过来调用C/C++的函数,这使得Lua在应用程序中可以被广泛应用。不仅仅作为扩展脚本,也可以作为普通的配置文件,代替XML,Ini等文件格式,并且更容易理解和维护。
--3. Lua由标准C编写而成,代码简洁优美,几乎在所有操作系统和平台上都可以编译,运行。
--4. 一个完整的Lua解释器不过200k,在目前所有脚本引擎中,Lua的速度是最快的。这一切都决定了Lua是作为嵌入式脚本的最佳选择。

ngx_lua_module是一个nginx http模块,它把lua解析器内嵌到nginx,用来解析并执行lua语言编写的网页后台脚本

这里主要是示范一下,如何在Nginx下安装lua-nginx-module模块

当然,如果你之前没有安装过Nginx,而且嫌安装麻烦,可直接下载openresty安装简单快捷,http://openresty.org/cn/installation.html(阿里的大牛章亦春的作品)

**步骤1)**下载安装LuaJIT 2.1(2.0或者2.1都是支持的,官方推荐2.1):http://luajit.org/download.html

[root@qianfeng01 ~]# cd /usr/local/src
[root@qianfeng01 src]# wget http://luajit.org/download/LuaJIT-2.1.0-beta2.tar.gz
[root@qianfeng01 src]# tar -zxvf LuaJIT-2.1.0-beta2.tar.gz
[root@qianfeng01 src]# cd LuaJIT-2.1.0-beta2
[root@qianfeng01 src]# make PREFIX=/usr/local/luajit
[root@qianfeng01 src]# make install PREFIX=/usr/local/luajit

别忘记配置环境变量
export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1

**步骤2)**下载并解压ngx_devel_kit(NDK)lua-nginx-module模块

[root@qianfeng01 ~]# cd /usr/local/nginx
wget https://github.com/simpl/ngx_devel_kit/archive/v0.2.19.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.14rc3.tar.gz
[root@qianfeng01 nginx]# tar  -zxvf v0.2.19.tar.gz
[root@qianfeng01 nginx]# tar  -zxvf v0.10.14rc3.tar.gz
[root@qianfeng01 nginx]# rm -rf  v0.2.19.tar.gz  0.10.14rc3.tar.gz


--官网:https://github.com/simpl/ngx_devel_kit/tags
	   https://github.com/openresty/lua-nginx-module/tags

步骤3) 带上两个模块重新编译nginx

如果不知道nginx的配置路径,可以使用nginx -V进行查询

[root@qianfeng01 ~]# cd /usr/local/nginx 
[root@qianfeng01 nginx]# ./configure \
    --prefix=/usr/local/nginx \
    --pid-path=/usr/local/nginx/tmp/nginx.pid \
    --lock-path=/usr/local/nginx/tmp/nginx.lock \
    --error-log-path=/usr/local/nginx/tmp/error.log \
    --http-log-path=/usr/local/nginx/tmp/access.log \
    --with-http_gzip_static_module \
    --http-client-body-temp-path=/usr/local/nginx/tmp/client \
    --http-proxy-temp-path=/usr/local/nginx/tmp/proxy \
    --http-fastcgi-temp-path=/usr/local/nginx/tmp//fastcgi \
    --http-uwsgi-temp-path=/usr/local/nginx/tmp/uwsgi \
    --http-scgi-temp-path=/usr/local/nginx/tmp/scgi \
    --add-module=/usr/local/nginx/echo-nginx-module-0.60 \
    --add-module=/usr/local/nginx/ngx_devel_kit-0.3.1rc1 \
    --add-module=/usr/local/nginx/lua-nginx-module-0.10.14rc3 
[root@qianfeng01 nginx]# make -j2
[root@qianfeng01 nginx]# make install

**步骤4)**测试配置文件

[root@qianfeng01 nginx]# nginx -c conf/my.conf -t
/usr/local/luaNginx/sbin/nginx: error while loading shared libraries: libluajit-4.1.so.2: cannot open shared object file: No such file or directory

如果出现以上错误提示,原因是因为lua模块没有引用到动态链接库。 需要我们手动设置一下
[root@qianfeng01 nginx]# vim /etc/ld.so.conf.d/libc.conf
/usr/local/luajit/lib

#重新加载
[root@qianfeng01 nginx]# ldconfig     

#再次测试就可以了

五 OpenResty的应用

官方地址:https://openresty.org/cn/rpm-packages.html

OpenResty 是一个强大的 Web 应用服务器,Web 开发人员可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,更主要的是在性能方面,OpenResty可以快速构造出足以胜任 10K 以上并发连接响应的超高性能 Web 应用系统。

5.1 OpenResty 安装

我们选择yum 安装方式, yum默认会安装openresty源的最新版本

yum -y install  yum-utils
# 添加openresty yum 源
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
# 安装openresty
yum  -y install openresty

注意:

1. yum方式安装后,安装目录在 /usr/local/openresty 
2. 同时可执行文件在 /usr/bin/openrestry,它只是一个软链接,因此没有必要再配置环境变量
# 查看可用版本
sudo yum list openresty --showduplicates 

5.2 OpenResty的用法

注意: 需要使用openresty指令,而不是nginx指令

常用方式:
openresty -p tempPath -c confPath  -t      用于测试:
openresty -p tempPath -c confPath		   启动
openresty -p tempPath -c confPath -s stop  关闭
openresty -p tempPath -c confPath -s quit  关闭
openresty -p tempPath -c confPath -s reload  启动后重新加载配置文件

-p tempPath:   产生的临时文件的目录,里面包含日志目录logs、pid文件等一些临时的内容
-c confPath:   配置文件的路径,相对于-p指定的路径而已。


如果使用-p指定了临时目录,那么要在-p所在的目录下创建个logs目录。
如果自己创建了配置文件的目录,那么应该将mime.types拷贝到此目录下。

比如:openresty -p /usr/local/openresty -c myconf/main.conf
应该提前在openresty下面创建logs和myconf。并将mime.types拷贝到myconf下。

5.3 OpenResty内置的Lua脚本语言

注意:openresty不需要单独安装lua安装包,因为是内置的。如果只安装了nginx,想使用lua需要单独安装。
5.3.1 注释语法
--单行注释

--[[
 多行注释
 多行注释
--]]
5.3.2 支持的数据类型
字符串类型,number类型,boolean类型,table类型(数组类型),nil类型(无类型)


print(type("Hello world"))      --> string
print(type(10.4*3))             --> number
print(type(print))              --> function
print(type(type))               --> function
print(type(true))               --> boolean
print(type(nil))                --> nil ,nil类型表示没有任何有效值
print(type(type(X)))            --> string
5.3.3 支持变量
[root@qianfeg01 ~]# vi test.lua

#!/usr/bin/lua

a = 5               -- 全局变量
local b = 5         -- 局部变量

function joke()
    c = 5           -- 全局变量,Lua中的变量全是全局变量,那怕是语句块或是函数里,除非用local显式声明为局部变量。
    local d = 6     -- 局部变量
end

joke()
print(c,d)          --> 5 nil

do 									-->do-end blocks解决变量作用域问题
    local a = 6     -- 局部变量
    b = 6           -- 对局部变量重新赋值
    print(a,b);     --> 6 6
end

print(a,b)      --> 5 6
[root@qianfeg01 ~]#  lua test.lua    
或者
[root@qianfeg01 ~]#   chmod 500 test.lua
[root@qianfeg01 ~]#   ./test.lua
5.3.4 各种类型的测试
[root@qianfeg01 ~]#  lua
> username=wangcongming							<----字符串赋值语法错误
> print(username)
nil	
> username='wangcongming'						<----字符串赋值可以使用单引号
> print(username)
wangcongming
> username="aaaaaaawangcongming"				<----字符串赋值可以使用双引号
> print(username)
aaaaaaawangcongming
> username=[[aaaaaaawangcongmingaaaaaaaaaa]]	<----字符串赋值可以使用双中括号
> print(username)
aaaaaaawangcongmingaaaaaaaaaa
> username=[["aaaaaaawangcongmingaaaaaaaaaa"]] 
> print(username)
"aaaaaaawangcongmingaaaaaaaaaa"    				<----双中括号里的字符都是普通字符
> passwod=[["aaaa								<----多行赋值方式
>> bbbb
>> cccc"]]
> print(passwod)
"aaaa
bbbb
cccc"							
> str="aaaa"
> str1="bbb"
> print(str..str1)								<----字符串进行拼接操作,使用..				
aaaabbb
> print(str.."-"..str1)							<----字符串进行拼接操作,使用..
aaaa-bbb
> username="aaaaaaaaaaaa"
> user=username								<----变量之间赋值
> print(user)
aaaaaaaaaaaa



--  数字的测试
> a = 5
> print(a)
5
> return a
5
> c = 7
> print (a+c)
12

> b = "20"
> return type(b)
string
> return type(tonumber(b))
number


--table的用法
> hobby={"book","movie","ball"}
> print(hobby)
table: 0x1cffa40
> print(hobby[0])
nil
> print(hobby[1])
book
> print(hobby[2])
movie
> print(hobby[3])
ball
> print(hobby[4])
nil
> hobby[4]="shop"
> print(hobby[4])
shop
> hobby["username"]="wangcongming"
> print(hobby["username"])
wangcongming
> index=10
> hobby[index]="gaoyuanyuan"
> print(hobby[index])
gaoyuanyuan
> print(hobby[10])
gaoyuanyuan
> print(hobby[9])
nil
> hobby={"movie","book","music"}    
> print(#hobby)      <----变量之间赋值
3


注意:table类型的访问需要使用索引,默认情况下索引从1开始。索引也可以是其他类型的值,就可以理解为键值对。
数字索引不需要连续,比如 a[1] = "aa" a[2] = "bb" a[4]= "cc"
5.3.5 if分支
--Lua认为false和nil为假,true和非nil为真
--[ 0 为 true ]
if(1)
then
    print("0 为 true")
end

两个分枝

if(布尔表达式)
then
   --[ 布尔表达式为 true 时执行该语句块 --]
else
   --[ 布尔表达式为 false 时执行该语句块 --]
end

多分枝

a=11
b=11
if(a>b)
then
    print("a>b")
elseif(a==b)
then
    print("a=b")  
else
    print("a<b")
end
5.3.6 循环结构的用法
--var 从 exp1 变化到 exp2,每次变化以 exp3 为步长递增,并执行一次 "执行体"。
--exp3 是可选的,如果不指定,默认为1。
for var=exp1,exp2,exp3 do  
    <执行体>  
end 

> for var=1,10,4 do print(var) end
1
4
7
10
> for var=1,10 do print(var) end
1
2
3
4
5
6
7
8
9
10
> hobby={"book","movie","ball"}
> hobby["hello"]="world"
> for k,v in pairs(hobby) do print(k..':'..v) end
1:book
2:movie
3:ball
hello:world

5.4 Lua-Nginx-Module常用的指令

参考:https://github.com/openresty/lua-nginx-module/

1)lua_code_cache

语法:lua_code_cache on | off
默认: on
适用上下文:http、server、location、location if
这个指令是指定是否开启lua的代码编译缓存,开发时可以设置为off,以便lua文件实时生效,如果是生产线上,为了性能,建议开启。

2)lua_package_path

语法:lua_package_path <lua-style-path-str>
默认:由lua的环境变量决定
适用上下文:http
设置lua代码的寻找目录。

例如:lua_package_path "/opt/nginx/conf/www/?.lua;;"; 具体的路径设置要参考lua的模块机制

3)init_by_lua(_file)

语法:init_by_lua <lua-script-str>
适用上下文:http

初始化一些lua的全局变量,以便后续的代码使用
http{
    init_by_lua 'cjson = require "cjson"';
    server {
        location = /api {
            content_by_lua '
                ngx.say(cjson.encode({dog = 5, cat = 6}))
            ';
        }
    }
}    

4)init_worker_by_lua(_file)

类似于上面的,不过是作用在work进程的,先于work进程启动而调用。

5)set_by_lua(_file)

语法: set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]

适用上下文:server、server if 、location、location if

警告 自从v0.9.17发行版以来,不鼓励使用此指令;请改用新的set_by_lua_block指令。
location /foo {
        set $diff ''; # we have to predefine the $diff variable here

        set_by_lua $sum '
            local a = 32
            local b = 56
 
            ngx.var.diff = a - b;  -- write to $diff directly
            return a + b;          -- return the $sum value normally
        ';
        echo "sum = $sum, diff = $diff";
}

6)content_by_lua(_file)

语法:content_by_lua <lua-script-str>

适用上下文:location、location if
        location =/mytest {
             default_type text/html; # 消息头
             set $num2 "56";
             content_by_lua "
        				ngx.print(ngx.var['arg_pwd']) 
        				ngx.print(ngx.var['arg_uname'])
               			ngx.print(ngx.null)
                		ngx.say(ngx.var['arg_pwd'])
             ";
        }


尝试访问地址:/mytest?pwd=123123&uname=michael

通过这个指令,可以由lua直接确定nginx响应页面的正文。

5.5 Lua-Nginx-Module中Nginx API常量与参数

Nginx Lua API只能在*_by_lua,*_by_lua_block和*_by_lua_file配置指令的上下文中运行的用户Lua代码中调用 。

1)ngx.arg

语法:value = ngx.arg[index]

上下文: set_by_lua*, body_filter_by_lua*

描述:当在set_by_lua *指令的上下文中使用时,此表是只读的,并保存config指令的输入参数:
value = ngx.arg[n]
        location /foo_sum {
                set $a 32;
                set $b 56;
                set_by_lua $sum ' return ngx.arg[1] + ngx.arg[2] '  $a  $b;
                echo "sum = ${sum}";
        }

2)ngx.null

ngx.null常量是一个NULL light用户数据,通常用于在Lua表等中表示nil值,类似于lua-cjson库的cjson.null常量。

3)ngx.var.VARIABLE

语法:ngx.var.VARIABLE_NAME

上下文:set_by_lua, rewrite_by_lua, access_by_lua*,content_by_lua, header_filter_by_lua*, body_filter_by_lua, log_by_lua*

读取和写入Nginx的变量值。
取值:value = ngx.var.password
赋值:ngx.var.password = value

注意,只有已经定义的nginx变量可以写入,也就是说,nginx变量不能在运行中创建。

        location /foo {
             set $pwd ''; # this line is required to create $my_var at config time
             content_by_lua_block {
                 ngx.var.pwd = 123;
        		 ngx.say(ngx.var.pwd);
             }
        }

面的正文。

5.5 Lua-Nginx-Module中Nginx API常量与参数

Nginx Lua API只能在*_by_lua,*_by_lua_block和*_by_lua_file配置指令的上下文中运行的用户Lua代码中调用 。

1)ngx.arg

语法:value = ngx.arg[index]

上下文: set_by_lua*, body_filter_by_lua*

描述:当在set_by_lua *指令的上下文中使用时,此表是只读的,并保存config指令的输入参数:
value = ngx.arg[n]
        location /foo_sum {
                set $a 32;
                set $b 56;
                set_by_lua $sum ' return ngx.arg[1] + ngx.arg[2] '  $a  $b;
                echo "sum = ${sum}";
        }

2)ngx.null

ngx.null常量是一个NULL light用户数据,通常用于在Lua表等中表示nil值,类似于lua-cjson库的cjson.null常量。

3)ngx.var.VARIABLE

语法:ngx.var.VARIABLE_NAME

上下文:set_by_lua, rewrite_by_lua, access_by_lua*,content_by_lua, header_filter_by_lua*, body_filter_by_lua, log_by_lua*

读取和写入Nginx的变量值。
取值:value = ngx.var.password
赋值:ngx.var.password = value

注意,只有已经定义的nginx变量可以写入,也就是说,nginx变量不能在运行中创建。

        location /foo {
             set $pwd ''; # this line is required to create $my_var at config time
             content_by_lua_block {
                 ngx.var.pwd = 123;
        		 ngx.say(ngx.var.pwd);
             }
        }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值