安装好Openresty后进入openresty的./nginx/conf/nginx.conf修改配置文件。
如下:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8090;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /hx/ {
default_type 'application/json';
--lua脚本代码块
content_by_lua_block {
--从openstry库中获取json序列化的包使用
local cjson = require "cjson"
ngx.req.read_body()
local body_data = ngx.req.get_body_data()
local post_data = body_data
--打日志到./ngixn/logs/error.log文件(./以openstry安装目录为准)
ngx.log(ngx.ERR,"获取到的请求参数为: ",post_data)
local parent_uri = ngx.var.uri
ngx.log(ngx.ERR,"父请求的请求路径为: ",parent_uri)
--替换路径/hx=>/sit2...
local sit2_path = string.gsub(parent_uri, "/hx", "/sit2")
local sit_path = string.gsub(parent_uri, "/hx", "/sit")
ngx.log(ngx.ERR,"=====开始访问sit,请求子请求sit的路径为: ",sit_path,"=====")
--发送子请求()需要下面配置了location模块才有用(注意location的配置规则)
local res = ngx.location.capture(sit_path,{
method = ngx.HTTP_POST,
body = post_data,
headers = {
['Content-Type'] = "application/json",
["Content-Length"] = #post_data
}
}
)
ngx.log(ngx.ERR,"=====开始访问sit2,请求子请求sit2的路径为: ",sit2_path,"=====")
local res2 = ngx.location.capture(sit2_path,{
method = ngx.HTTP_POST,
body = post_data,
headers = {
['Content-Type'] = "application/json",
["Content-Length"] = #post_data
}
}
)
ngx.log(ngx.ERR,"sit2 res2: ",cjson.encode(res2.body))
ngx.status = res.status
ngx.log(ngx.ERR,"sit res: ",cjson.encode(res.body))
ngx.say(res.body)
}
}
location /sit/ {
default_type 'application/json';
proxy_pass http://12.99.108.178:9001/;
}
location /sit2/ {
default_type 'application/json';
proxy_pass http://12.103.47.108:9001/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
修改后启动配置文件。配置文件中的注释都可以删除掉。