安装
(1)wget https://openresty.org/download/openresty-1.15.8.1.tar.gz #下载源码安装包
(2)tar -zxvf openresty-1.15.8.1.tar.gz #解压
(3)./configure --without-http_redis2_module --with-http_iconv_module #选择需要的插件启用, --with-Components 激活组件,–without 则是禁止组件
(4)make && make install #编译加安装
(5)vi /etc/profile #加入path路径
(6)export PATH=$PATH:/usr/local/openresty/nginx/sbin/ #加入的内容
(7)source /etc/profile ##使配置生效
启动
启动的是nginx,而非有专门的openresty
启动方式:./nginx
其他指令:./nginx -s reload 重载配置 ./nginx -s stop 停止
Nginx配置
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#指定template.lua中html文件所在的根目录
set $template_root /usr/local/openresty/nginx/html/tempaltes;
location / {
root html;
index index.html index.htm;
default_type text/html;
#载入指定lua程序
#content_by_lua_file /usr/local/openresty/nginx/conf/lua/http.lua;
content_by_lua_file /usr/local/openresty/nginx/conf/lua/template.lua;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
集成常用模块
Redis模块
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
local res, err = red:auth("haydn")
if not res then
ngx.say("failed to authenticate: ", err)
return
end
red:set("dog", "an animal")
local dog = red:get("dog")
ngx.say("failed to get dog: ", err)
HTTP模块
-- 获取URL中的参数对
local arg = ngx.req.get_uri_args()
for k,v in pairs(arg) do
ngx.say("[GET ] key : ",k," v: ",v,"<br>")
end
-- 读取响应体
ngx.req.read_body()
local arg = ngx.req.get_post_args()
for k,v in pairs(arg) do
ngx.say("[POST ] key : ",k," v: ",v,"<br>")
end
-- 获取响应头
local headers = ngx.req.get_headers()
for k,v in pairs(headers) do
ngx.say("[Header ] key : ",k," v: ",v,"<br>")
end
-- 获取响应体数据
local body = ngx.req.get_body_data()
ngx.say("[Body ]",data)
模板渲染模块
template.lua
-- 同时集成redis,动态获取数据
local template = require "resty.template"
local redis = require "resty.redis"
local red = redis:new()
red:connect("127.0.0.1", 6379)
red:auth("haydn")
data = {
name = "<h1>haydn</h1>",
tall = red:get("tall")
}
-- 这个view.html的位置应该在nginx配置文件中template_root指定的目录下
template.render("view.html",data)
view.lua
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>{{name}}</h1><!-- 不会转义html标签 -->
<h1>{*name*}</h1><!-- 会转义html标签 -->
{{tall}}
</body>
</html>
注意:以上lua脚本都引用了openresty的模块,所以必须在openresty环境下执行,直接用lua xx.lua将无法执行
集成第三方模块
组件列表,找到组件在git的仓库,复制其lua脚本到openresty/resty下即可
--使用方式
local xxxx = require "resty.xxxx"