9 Mar 2019

A URL Shortener with Analytics Based on Nginx and Redis

Overview

URL shortening converts lengthy URLs into substantially shorter versions while maintaining redirect functionality to the original page — for example, https://example.com/assets/category_B/Foo/ becomes https://snip.ml/Foo. This is useful for character-limited messaging, print media references, memorable links, and permanent URLs.

Setup

  • Start a Redis instance.
  • Build Nginx with lua-nginx-module and set-misc-nginx-module.
  • Copy the Lua script from conf/lua/n3r/urlshortener_eval.lua to your Nginx conf/lua/n3r/ directory, and update the Redis configuration in the connect function.
  • Copy html/shorten-ui.html to your Nginx html directory.
  • Download lua-resty-redis and place lib/resty/redis.lua in your Nginx conf/lua/resty/ directory.
  • Add configuration to nginx.conf: lua_package_path in the HTTP block, and location blocks for shorten-ui.html, shorten, and the short-URL pattern match.

Basic usage

Create a short URL:

http://localhost:8088/shorten?url=http://www.google.com

Note: include the http:// prefix in the url parameter.

Visit the shortened URL: just access the returned short link.

Web UI:

http://localhost:8088/shorten-ui.html

Create a random short URL:

http://localhost:8088/shorten?url=http://www.google.com&random=true

Query the original URL:

http://localhost:8088/shorten-qrybyshort?url=http://t.cn/0asd

Source code: github.com/mouryaamit/Nginx-URL-Shortener