nginx+redis +lua脚本实现nginx 302临时跳转
实现过程:nginx+redis +lua的环境,前一篇博文已经部署好
在服务器上安装好redis后,记得要安装php的redis扩展,由于开发语言是php,所以要安装redis的扩展,这样才能php程序操作redis,
php脚本存入key到redis中,通过请求url来实现nginx 302跳转
在nginx.conf文件中http标签添加如下内容:
# grep lua /usr/local/nginx/conf/nginx.conf lua_package_path "/usr/local/nginx/lua/lua-resty-redis/lib/?.lua;;";
lua_shared_dict cache_ngx 128m;
# grep vhost /usr/local/nginx/conf/nginx.conf
include vhost/*.conf;
配置nginx虚拟主机www.iuiodp.cn.conf
# cat /usr/local/nginx/conf/vhost/www.iuiodp.cn.conf
server {
listen 80;
server_namewww.iuiodp.cn iuiodp.cn;
index index.html index.htm index.php;
root /data/www/www.iuiodp.cn;
location ~ .*\.(php|php5)?$
{
#fastcgi_pass127.0.0.1:9000;
fastcgi_passunix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
location / {
* contentbyluafile /usr/local/nginx/conf/lua/csu.lua;*
}
access_log/data/wwwlogs/iuiodp.cn_access.log;
}
在location段中指定csu.lu脚本路径:
location / { content_by_lua_file /usr/local/nginx/conf/lua/csu.lua;
}
csu.lua脚本如下:
# cat /usr/local/nginx/conf/lua/csu.lua
local redis = require "resty.redis"
local cache = redis.new()
cache.connect(cache, '127.0.0.1', '6379')
local key = ngx.var.uri;
local res = cache:get(key)
if res == ngx.null then
local res = cache:get("/sp");
ngx.redirect(res)
else
ngx.redirect(res)
end
服务器hosts文件本地解析:
# grep www.iuiodp.cn /etc/hosts
21.15.1.44 www.iuiodp.cn
登录redis 写入key值:
# redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> get /
(nil)
127.0.0.1:6379> set / http://www.yt925.com
OK
127.0.0.1:6379> get /
"http://www.yt925.com"
127.0.0.1:6379> set /a http://www.jd.com
OK
127.0.0.1:6379> get /a
"http://www.jd.com"
127.0.0.1:6379>
127.0.0.1:6379> set /d http://www.test.com
OK
127.0.0.1:6379> get /d
"http://www.test.com"
服务器上curl域名,实现了302临时跳转
# curl http://www.iuiodp.cn
302 Found
302 Found
nginx
# curl http://www.iuiodp.cn/a
302 Found
302 Found
nginx
# curl http://www.iuiodp.cn/d
302 Found
302 Found
nginx
windows本地hosts文件绑定21.15.1.44 www.iuiodp.cn
浏览器请求www.iuiodp.cn 会直接跳转到http://www.yt925.com 这个网站的页面
浏览器请求http://www.iuiodp.cn/a 会直接跳转到https://www.jd.com 官网页面
浏览器请求http://www.iuiodp.cn/d会直接跳转到https://www.test.com 官网页面
访问日志如下:
演示到此处,跳转功能已经实现,尽情关注后续的博文,后续还有精彩的内容。同时也希望大家能互相交流学习
页:
[1]