通过openresty 设置proxy set header
- 背景: work组需要通过以请求的url参数做结构化,然后设置到proxy header里,通过header透传来实现路由规则。但是由于xxl-admin发送的是post请求,无法获取url参数。所以这一方案行不通。于是考虑用openresty从redis取值来实现。下面的测试成功的方案。
## 设置key,value
[root@ghd_6_78 openrestry-conf]# redis-cli -h 100.100.100.100 -p 6379 get foo
"hello,lkd"
## 从redis 获取value的lua脚本
[root@ghd_6_78 openrestry-conf]# cat test.lua
local redis = require "resty.redis"
local cache = redis.new()
cache.connect(cache, '100.100.100.100', '6379')
local res = cache:get("foo")
if res==ngx.null then
ngx.say("This is Null")
return
end
ngx.var.ghdvar = res
## nginx 配置
[root@ghd_6_78 openrestry-conf]# grep -A6 'test6' default.conf
location /test6 {
set $ghdvar '';
rewrite_by_lua_file /etc/nginx/conf.d/test.lua;
proxy_pass http://172.16.6.166;
proxy_set_header X-my-var $ghdvar;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
[root@ghd_6_78 openrestry-conf]#
## 抓包验证
17:25:36.557420 IP (tos 0x0, ttl 63, id 39501, offset 0, flags [DF], proto TCP (6), length 504)
100.100.100.100.56788 > 172.16.6.166.80: Flags [P.], cksum 0xaa5f (correct), seq 0:452, ack 1, win 229, options [nop,nop,TS val 3548694890 ecr 2923139701], length 452: HTTP, length: 452
GET /test6 HTTP/1.0
X-my-var: hello,lkd
Host: 172.16.6.166
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
镜像相关
docker pull openresty/openresty:1.15.8.2-7-centos
预处理
mkdir -p /root/openresty-conf
docker cp openresty-test:/etc/nginx.conf.d/. /root/openresty-conf/.
脚本:
[root@ghd_6_78 ~]# cat nginx_lua.sh
#!/bin/sh
docker run -d --name openresty-test -p 9096:80 -v /root/openrestry-conf:/etc/nginx/conf.d openresty/openresty:1.15.8.2-7-centos