OpenResty使用实例
OpenResty是什么
-
OpenResty是什么,官网是这样介绍的:
通过 Lua 扩展 NGINX 实现的可伸缩的 Web 平台
-
的确,OpenResty可以简单的理解为Nginx + Lua,通过Lua库引入数据库访问能力,真正的让Nginx向搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关这一目标迈出了重要的一步
OpenResty的配置
- OpenResty的配置可以分为2类
- lua脚本
- Nginx配置文件
- 下面列举几个常见场景的Nginx配置
静态文件(页面)服务器配置
server {
listen 80;
server_name ${hostname};
rewrite ^(.*)$ https://${hostname}$1 permanent;
}
server {
listen 443;
server_name ${hostname};
# ssl证书文件位置(常见证书文件格式为:crt/pem)
ssl_certificate /etc/nginx/ssl/${hostname}.pem;
# ssl证书key位置
ssl_certificate_key /etc/nginx/ssl/${hostname}.key;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
root /etc/nginx/dist;
index index.html index.htm;
}
- 将静态页面文件映射到OpenResty容器内的
/etc/nginx/dist
内即可
反向代理
server {
listen 80;
server_name ${hostname};
rewrite ^(.*)$ https://${hostname}$1 permanent;
}
server {
listen 443 ssl;
server_name ${hostname};
# ssl证书文件位置(常见证书文件格式为:crt/pem)
ssl_certificate /etc/nginx/ssl/auth-cert.pem;
# ssl证书key位置
ssl_certificate_key /etc/nginx/ssl/auth-cert.key;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'Upgrade';
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://${target}/;
}
}
- ${target}就是反向代理的目标服务器地址或域名,注意不要丢掉后边的
/
动态路由设置
- 需求说明:根据请求参数动态转发到不同的服务器、端口,比如
hostname/users/1/info/2
转发到hosname1:9200
,hostname/users/3/info/4
转发到hostname2:8080
-
在
/opt/openresty/lua/
目录下创建split.lua
echo ' --[[ 拆分字符串 e.g. /a/b/c table[1] a table[2] b table[3] c --]] function split(str, pat) local t = { } local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t, cap) end last_end = e + 1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str: