本文共 2787 字,大约阅读时间需要 9 分钟。
nginx+redis +lua的环境,前一篇博文已经部署好
在服务器上安装好redis后,记得要安装php的redis扩展,由于开发语言是php,所以要安装redis的扩展,这样才能php程序操作redis,php脚本存入key到redis中,通过请求url来实现nginx 302跳转在nginx.conf文件中http标签添加如下内容:
[root@localhost ~]# 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;[root@localhost ~]# grep vhost /usr/local/nginx/conf/nginx.confinclude vhost/*.conf;
配置nginx虚拟主机www.iuiodp.cn.conf
[root@localhost ~]# cat /usr/local/nginx/conf/vhost/www.iuiodp.cn.conf server { listen 80; server_name www.iuiodp.cn iuiodp.cn; index index.html index.htm index.php; root /data/www/www.iuiodp.cn; location ~ .*\.(php|php5)?$ { #fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/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脚本如下:
[root@localhost ~]# cat /usr/local/nginx/conf/lua/csu.lualocal 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 thenlocal res = cache:get("/sp");ngx.redirect(res)elsengx.redirect(res)end
服务器hosts文件本地解析:
[root@localhost ~]# grep www.iuiodp.cn /etc/hosts21.15.1.44 www.iuiodp.cn
登录redis 写入key值:
[root@localhost ~]# redis-cli -h 127.0.0.1 -p 6379127.0.0.1:6379> get /(nil)127.0.0.1:6379> set / http://www.yt925.comOK127.0.0.1:6379> get /"http://www.yt925.com"127.0.0.1:6379> set /a http://www.jd.comOK127.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.comOK127.0.0.1:6379> get /d"http://www.test.com"
服务器上curl域名,实现了302临时跳转
[root@localhost ~]# curl http://www.iuiodp.cn302 Found 302 Found
nginx [root@localhost ~]# curl http://www.iuiodp.cn/a302 Found 302 Found
nginx [root@localhost wwwlogs]# curl http://www.iuiodp.cn/d302 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 官网页面
访问日志如下:
演示到此处,跳转功能已经实现,尽情关注后续的博文,后续还有精彩的内容。同时也希望大家能互相交流学习
转载于:https://blog.51cto.com/wujianwei/2123329