一、介绍

某些业务场景需要给客户发送短信,短信中包括营销的链接,希望链接为短链接模式,跳转到正常长链接。

二、准备

  • OpenResty
  • Redis

三、实现步骤

1、 创建short_uri.lua脚本

在/opt/openresty/1.13.6.1/nginx/conf/lua下创建short_uri.lua脚本

local redis = require "resty.redis"
local conn = redis:new()
conn:set_timeout(2000)
local ok, err = conn:connect("10.xxx.xxx.xxx","6379")
conn:auth("root123.")
if not ok then
  ngx.say("failed to connect : ", err)
  conn.close()
  return
end
local request_uri = string.match(ngx.var.request_uri, ".*", 2)
local res, err = conn:get("SHORT-URI-"..request_uri);
if res ~= ngx.null then
  return ngx.redirect(res, 301)
else
  ngx.exit(ngx.HTTP_FORBIDDEN)
  conn.close()
  return
end

2、 修改配置文件nginx.conf

location / {
    root   html;
    index  index.html index.htm;
}

修改为

location / {
   content_by_lua_file conf/lua/short_uri.lua;
}

3、 设置Redis

在redis中设置几个链接

127.0.0.1:6379> set SHORT-URI-xd4Xdhs /backend/admin/log
127.0.0.1:6379> set SHORT-URI-abcd http://www.baidu.com

4、 测试

  • http://10.xxx.xxx.xxx/xxxxx
403 Forbidden
  • http://10.xxx.xxx.xxx/xd4Xdhs

跳转到

http://10.xxx.xxx.xxx/backend/admin/log
  • http://10.xxx.xxx.xxx/abcd

跳转到

https://www.baidu.com/

更多推荐