NOTE
Designing a Short URL System
A historical note on mapping long URLs to short codes with Redis and Base62.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is a Short URL?
Convert a normal URL into a shorter URL.
2. Why Do We Need Short URLs?
They are short and convenient to publish.
3. Short URL System Design
Assume the URI of the short URL system is http://t.cn.
3.1. Write Process
- Enter the long URL to convert:
http://www.example.com. - Query Redis to see whether a short URL corresponding to
www.example.comalready exists. If it does, return it. - If not, use Redis auto-increment to generate an ID.
- Convert the incremented value to Base62. Assume the resulting Base62 value is
RlB2PdD.- When converting from a lower base to a higher base, the number of characters decreases.
- Store the mapping between
RlB2PdDandwww.example.comin Redis.
3.2. Query Process
- Enter
http://t.cn/RlB2PdDin the browser. - DNS first resolves the IP address of
http://t.cn. - After DNS gets the IP address, for example
74.125.225.72, it sends an HTTP GET request to that address to query the short codeRlB2PdD. - The
http://t.cnserver gets the corresponding long URL through the short codeRlB2PdD. - The request is redirected with HTTP 301 to the corresponding long URL
http://www.example.com(this uses the browser mechanism; if there is front-end cooperation, returninghttp://www.example.comis enough and the front end can redirect by itself).- 301 is a permanent redirect because a short address does not change once generated, and it also reduces server pressure.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub