一、Nginx的简介以及应用场景
1.1 简介
1. nginx 是一款轻量级的、高性能的,并发能力强的框架
2. 可以提供HTTP服务、反向代理服务、邮箱服务等功能
3. 由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点开发的、第一个版本是2004年10月4日发布的
4. 因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。
1.2 应用场景的应用
1. 可以应用于HTTP服务
2. 可以应用于虚拟主机
3. 可以应用于反向代理服务
4. 可以应用于负载均衡
5. 可以应用于动静分离(动态请求和静态请求的分离)
二、Nginx的安装和常用命令介绍
2.1 Nginx的安装
1)环境准备工作
-- 安装nginx需要提前准备好c语言环境
[root@qianfeng01 ~]# yum -y install gcc-c++
-- 还需要pcre和pcre-devel插件
[root@qianfeng01 ~]# yum install -y pcre pcre-devel
-- 再需要zlib压缩工具
[root@qianfeng01 ~]# yum install -y zlib zlib-devel
-- 最后还需要openssl相关工具
[root@qianfeng01 ~]# yum install -y openssl openssl-devel
2)上传、解压、更名
[root@qianfeng01 ~]# tar -zxvf nginx-1.8.0.tar.gz -C /usr/local/
[root@qianfeng01 ~]# cd /usr/local/
[root@qianfeng01 local]# mv nginx-1.8.0/ nginx
3)设置配置路径
[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
3)编译并安装
[root@qianfeng01 nginx]# make && make install
注意:只要出现sbin目录,就安装成功
4)配置环境变量,并校验
[root@qianfeng01 nginx]# vim /etc/profile
#nginx environment
export NGINX_HOME=/usr/local/nginx
export PATH=$NGINX_HOME/sbin:$PATH
[root@qianfeng01 nginx]# source /etc/profile
2.2 常用命令的介绍
[root@qianfeng01 ~]# 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
注意:配置文件里默认监听的端口号是80,主机名为localhost
如何启动nginx
[root@qianfeng01 ~]# nginx
启动后,可以在windows的浏览器上访问
192.168.10.101 直接回车, 出现welcome to nginx,表示启动成功。
当然也可以在linux 使用 netstat -nltp 查看80端口是否启用。
如何关闭nginx
[root@qianfeng01 ~]# nginx -s stop
2.3 配置文件的介绍
配置文件分三大部分:
第一部分:是从文件开始到events之前的部分,用于nginx的全局配置
第二部分: events模块,该模块用于指定nginx与用户连接的参数
第三部分:http模块,该模块是各个应用场景配置的主配置区域。
#user nobody;
worker_processes 1; #并发指令,用于指定nginx的并发数量
#error_log logs/error.log; # 错误指令,用于指定错误文件的位置和级别
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid; #pid指令,用于指定pid文件的位置
events {
worker_connections 1024; #连接指令,用于指定一次性可以有多少个客户端连接nginx
}
http {
include mime.types; # 用于引用其他文件,相当于java源文件中的import
default_type application/octet-stream; # 用于指定http处理的数据流格式
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
# log_format 用于指定日志文件的格式,同时并起一个昵称。
#access_log logs/access.log main; #用于指定访问日志的位置和格式
sendfile on; #on|off 开启和关闭
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on; #是否开启压缩 on|off
server {
listen 80; # 要监听的端口号
server_name localhost; # 要监听的ip或者是host
#charset koi8-r;
#access_log logs/host.access.log main;
location / { #用于指定客户端的访问请求路径要访问的服务器的root
root html; #用来指定root是哪里
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;
# }
#}
}
三、Nginx的应用案例配置(重点)
3.1 HTTP服务
nginx本身就是一个HTTP服务器,默认配置文件监听的是80端口,ip为localhost。默认访问的静态页面的root是--prefix下的html目录。
参考配置:
server {
listen 8089;
server_name 192.168.10.101;
location / {
root html;
#index用于指定访问的首页是谁
index file1.html;
}
error_page 500 502 503 504 403 /50x.html;
location = /50x.html {
root html;
}
}
并在html目录下创建file1.html文件
3.2 虚拟主机的应用
nginx可以用来配置模拟多台服务器,实现不同的访问请求。比如当客户端访问的地址如下:
192.168.10.101:8089 访问的是某一个目录下的file1.html
192.168.10.201:8089 访问的是另一个目录下的file2.html
步骤1) 配置linux的多个ip地址
[root@qianfeng01 html]# vim /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE="Ethernet"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
BOOTPROTO="none"
IPADDR="192.168.10.101"
IPADDR1=192.168.10.201 <==========追加一个IPADDR1
PREFIX="24"
GATEWAY="192.168.10.2"
DNS1="8.8.8.8"
DNS2="114.114.114.114"
[root@qianfeng01 html]# systemctl restart network
验证ip是否生效:
-- 第一步:在linux上ping 192.168.10.201
-- 第二步:在windows上的cmd里ping 192.168.10.201
步骤2)修改nginx的配置文件
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#设置第一个虚拟主机
server {
#设置端口
listen 8089;
# 设置ip
server_name 192.168.10.101;
location / {
# 指定根
root html;
#指定首页
index file1.html;
}
error_page 500 502 503 504 403 /50x.html;
location = /50x.html {
root html;
}
}
#设置第二个虚拟主机
server {
listen 8089;
server_name 192.168.10.201;
location / {
#注意:修改了根的位置是html1 需要主动创建出来
root html1;
#注意:在html1里创建一个文件file2.html
index file2.html;
}
error_page 500 502 503 504 403 /50x.html;
location = /50x.html {
root html;
}
}
}
步骤3)完善配置文件中的各个目录和文件
[root@qianfeng01 nginx]# mkdir html1
[root@qianfeng01 nginx]# vim html1/file2.html
注意:如果你上一个案例中修改了html下的file1.html为file2.html,那么需要更名回来
[root@qianfeng01 nginx]# mv ../html/file2.html ../html/file1.html
步骤4)重新加载nginx
[root@qianfeng01 html1]# nginx -c conf/nginx.conf -t
[root@qianfeng01 html1]# nginx -c conf/nginx.conf -s reload
注意:-c是相对--prefix的路径而言,而不是当前工作目录
步骤5)在浏览器上访问如下地址
http://192.168.10.101:8089/
http://192.168.10.201:8089/
3.3 反向代理
3.3.1 正向代理的概念
当用户想要访问目标服务器A时,但是访问不了,需要借助另外一台可以访问目标服务器的机器B。则机器B是正向代理服务器。 此时:用户是知道机器B在访问机器A。
3.3.2 反向代理的概念
3.3.3 nginx作为反向代理服务器的配置方案
步骤1)在三台linux上各搭建一个tomcat服务器,并启动
上传、解压、使用tomcat目录下的bin里的startup.sh启动服务,默认端口号是8080
先修改tomcat的主页面
[root@qianfeng01 ~]# vim /usr/local/apache-tomcat-7.0.47/webapps/ROOT/index.jsp
[root@qianfeng02 ~]# vim /usr/local/apache-tomcat-7.0.47/webapps/ROOT/index.jsp
[root@qianfeng03 ~]# vim /usr/local/apache-tomcat-7.0.47/webapps/ROOT/index.jsp
修改51行的内容,以作区分。
[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
[root@qianfeng03 ~]# netstat -ntlp
步骤2)修改nginx的配置文件
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream tomcat1 {
server 192.168.10.101:8080;
}
upstream tomcat2 {
server 192.168.10.102:8080;
}
upstream tomcat3 {
server 192.168.10.103:8080;
}
server {
listen 80;
server_name www.nginx111.com;
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.jd.com;
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;
location / {
proxy_pass http://tomcat3;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
步骤3)检查配置文件并重新加载
[root@qianfeng01 local]# nginx -t
[root@qianfeng01 local]# nginx -s reload
步骤4)修改window上的hosts文件
192.168.10.101 www.nginx111.com www.jd.com www.taobao.com
步骤5)测试
在浏览器上分别输入以下域名:
www.nginx111.com
www.jd.com
www.taobao.com
3.4 负载均衡
3.4.1 概念说明
当过多的请求被分发到某一个目标服务器时,该服务器容易出现宕机瘫痪。这属于“热点问题”,也就是负载不均衡。
因此在请求过多时,应该尽量做到每台服务器收到的请求差不多,或者性能好的多收一点,性能差的少收点。
-- nginx在反向代理的基础上,可以做负载均衡
3.4.2 配置方案
upstream tomcat1 {
server 192.168.10.101:8080 weight=10;
server 192.168.10.102:8080 weight=5;
server 192.168.10.103:8080 weight=1;
}
server {
listen 80;
server_name www.nginx111.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;
}
}
负载均衡的算法
1. round_robin(轮询):默认配置。
2. weight: 权重算法, 值越大,被分配的几率越大, 默认值是1
3. ip_hash: ip哈希算法,会使用客户端的ip做一个hash值算法,得到固定的值,每次访问的都是同一服务器
upstream backend {
ip_hash;
server server1;
server server2;
}
4. fair:根据后台响应时间来分发请求,响应时间短的分发的请求多。
upstream backend {
server server1;
server server2;
fair;
}
5. url_hash:根据请求的url的hash值将请求分到不同的机器中,当后台服务器为缓存的时候效率高。
upstream backend {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}
3.5 location的匹配用法
server里的location配置是用于匹配http协议的路径的,可以有以下匹配规则
#语法规则
location [=|~|~*|^~]/uri/ {
}
#示例
location / # 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default。
location =/uri # =开头表示精确匹配,只有完全匹配上才能生效。
location ~pattern # ~ 开头表示区分大小写的正则匹配。
location ~*pattern # ~*开头表示不区分大小写的正则匹配。
location ^~/uri # ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location /uri # 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后。
测试:
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.nginx111.com;
location / {
default_type text/plain;
return 200 "my girlfriend is gyy";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
浏览器访问:
http://qianfeng01:10086/abc.html
http://qianfeng01:10086/abcd.html
四、Nginx的其他内容
4.1 nginx的变量(重点)
4.1.1 说明
nginx框架中内置了很多常用的变量,以及支持自定义变量。
如何自定义变量?
1. 需要使用set指令
2. 变量名需要使用$开头
4.1.2 内置变量(熟悉)
$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
修改nginx的配置文件
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8090;
server_name 192.168.10.101;
location / {
# 指定服务器向客户端返回的数据类型,为html文本
default_type "text/html";
# 自定义变量
set $hobby "movie";
# 使用echo指令向客户端返回信息,其中有内置变量和自定义变量的值
echo "$http_user_agent $remote_addr $remote_port $args $hobby";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
重写加载配置文件:
nginx -s reload
测试:在浏览器上输入以下地址,查看返回信息
http://192.168.10.101:8090/?username=wcm
4.2 日志指令、进程说明、lua脚本
4.2.1 日志指令
log_format : 用来规定采集日志的格式 以及格式名称
语法: log_format logname logformat
access_log: 用来指定采集日志的存储路径,以及格式名称
error_log: 用来指定错误日志的存储路径以及级别
4.2.2 进程说明
nginx中有两类进程,一类是master,一类是worker
master是nginx的主进程,也叫管理进程,只能有一个
worker是真正负责处理请求的进程,称之为工作进程,可以有多个
4.2.3 lua脚本的简介
##扩展阅读》》lua脚本语言介绍
--1. Lua是一个小巧的脚本语言。作者是巴西人。该语言的设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。
--2. Lua脚本可以很容易的被C/C++代码调用,也可以反过来调用C/C++的函数,这使得Lua在应用程序中可以被广泛应用。不仅仅作为扩展脚本,也可以作为普通的配置文件,代替XML,Ini等文件格式,并且更容易理解和维护。
--3. Lua由标准C编写而成,代码简洁优美,几乎在所有操作系统和平台上都可以编译,运行。
--4. 一个完整的Lua解释器不过200k,在目前所有脚本引擎中,Lua的速度是最快的。这一切都决定了Lua是作为嵌入式脚本的最佳选择。
注意:nginx需要单独安装ngx_lua_modul模块,才能支持lua脚本语言
五、OpenResty的应用
官方地址:https://openresty.org/cn/rpm-packages.html
OpenResty 是一个强大的 Web 应用服务器,Web 开发人员可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,更主要的是在性能方面,OpenResty可以快速构造出足以胜任 10K 以上并发连接响应的超高性能 Web 应用系统。
5.1 OpenResty的安装
步骤1)安装yum-utils
yum -y install yum-utils
步骤2)配置openresty的yum源
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
步骤3)安装openresty
yum -y install openresty
小贴士:
1. 安装完openresty后, 之前安装的nginx可以不用了。
2. 内置了nginx以及lua模块
3. openresty的bin目录下有一个可执行脚本openresty, 本质是一个链接到内置nginx的启动脚本文件的软链接
4. 不需要配置环境变量,因为在安装时,已经在/usr/bin里生成了软连接。 所以,如果想要使用内置的nginx,只需要使用openresty即可。
5.2 OpenResty的常用指令(重点)
小贴士:使用openresty指令,本质就是在使用nginx指令,所以指令信息如下:
[root@qianfeng01 ~]# openresty -h
nginx version: openresty/1.19.9.1
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
[-e filename] [-c filename] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it 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/openresty/nginx/)
-e filename : set error log file (default: logs/error.log)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file
其实常用的就是 -t -s -c -p
如果使用-p指定了临时目录,那么要在-p所在的目录下创建个logs目录。
如果自己创建了配置文件的目录,那么应该将mime.types拷贝到此目录下。
比如:openresty -p /usr/local/openresty -c myconf/main.conf
应该提前在openresty下面创建logs和myconf。并将mime.types拷贝到myconf下。
5.3 lua脚本语言的介绍(熟悉)
5.3.1 简单说明
该脚本语言支持变量、分支结构、循环结构、数组、函数等语法。支持的数据类型有number类型、string类型、table类型、boolean类型、nil类型
1. 注释的语法:
单行注释: --
多行注释: --[[
--]]
2. 变量的用法和shell中一样,不需要指定类型.
3. 直接在shell的命令行上输入lua脚本,直接进入lua命令行
4. 常用函数有type(),print()
5.3.2 基本语法的演示
1)类型的查看
> name='wcm'
> print(type(name))
string
> name="gyy"
> print(type(name))
string
> print(type("aaaa"))
string
> print(type(1.0))
number
> print(type(false))
boolean
> print(type(aaaa))
nil -- nil是lua中的一种特殊类型,表示无类型。
> print(type(print))
function
>
2)数据类型的演示
----------------------字符串-----------------
> username = "wangcongming"
> print(username)
wangcongming
> username = 'wangcongming'
> othername=username
> print(othername)
wangcongming
> hobby=[[aaaaa]]
> print(hobby)
aaaaa
> hobby=[['aaaaa']]
> print(hobby)
'aaaaa'
> hobby=[[
>> aa
>> bb
>> cc
>> dd
>> ]]
> print(hobby)
aa
bb
cc
dd
> a1="hello"
> b1="world"
> print(a1..b1)
helloworld
>
---------------number类型的演示---------------------
> a=1
> b=2
> print(a+b)
3
> print(a*b)
2
> print(a/b)
0.5
> print(a%b)
1
> print(a++)
stdin:1: unexpected symbol near '+'
> c=2.4
> print(a+c)
3.4
>
------------boolean类型-----------------
> a=1
> b=2
> print(a==b)
false
> print(a~=b)
true
--------------table类型(表类型,可以理解为数组类型)----------------------------
> hobbys={
"movie","muic",18}
> print(hobbys)
table: 0x14dd050
> print(hobbys[0])
nil --下标从1开始
> print(hobbys[1])
movie
> print(hobbys[3])
18
> print(hobbys[4])
nil
> hobbys[10]="aaa"
> print(#hobbys)
3 -- 赋值时,下标不连续,长度不识别,只识别连续的长度
> hobbys[4]=23
> print(#hobbys)
4
> hobbys["name"]="canglaoshi" -- 下标可以使用字符串
> print(hobbys["name"])
canglaoshi
5.3.3 分支和循环结构
1)分支结构
--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
2) 循环结构的用法
--var 从 exp1 变化到 exp2,每次变化以 exp3 为步长递增,并执行一次 "执行体"。
--exp3 是可选的,如果不指定,默认为1。
for var=exp1,exp2,exp3 do
<执行体>
end
> for var=1,10,3 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.3.4 函数
[root@qianfeng01 ~]# vim test2.lua
#!/usr/bin/lua
function cal()
sum=0
for num=1,100 do
sum=sum+num
end
print(sum)
end
cal()
[root@qianfeng01 ~]# lua test2.lua
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/test1.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 );
}
}
总结:
变量的使用:
set 可以自定义变量
set $变量名 '变量值'
使用变量方式1: $变量名
使用变量方法2: ngx.var.变量名
使用变量方法3: ngx.arg[n]
使用变量方式4: $arg_name 注意:name指的是浏览器请求路径中的键值对 比如 ..../login.do?username=wcm
如果想要获取username的值, 要写成$arg_username
et_by_lua *指令的上下文中使用时,此表是只读的,并保存config指令的输入参数:
value = ngx.arg[n]
```nginx
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 );
}
}
总结:
变量的使用:
set 可以自定义变量
set $变量名 '变量值'
使用变量方式1: $变量名
使用变量方法2: ngx.var.变量名
使用变量方法3: ngx.arg[n]
使用变量方式4: $arg_name 注意:name指的是浏览器请求路径中的键值对 比如 ..../login.do?username=wcm
如果想要获取username的值, 要写成$arg_username