短连接算法实现以及php结合redis、nginx大概流程
短连接的好处
- 简单方便,利于推广
- http传输好了很多,有助于带宽节约和高并发
- 防止尾巴参数泄密,不安全
大概实现流程
- 短连接算法(新浪短连接算法),一对四,生成四个链接,随机取出一个
- 映射匹配(redis的hash或者string),如用hash存储,key=加密串,value=真实url
- 短链接发起请求、解析短连接、跳转真实长连接
//加密代码
<?php class Short_Url { #字符表 public static $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; public static function short($url) { $key = "alexis"; $short_url_list = array(); $urlhash = md5($key . $url); $len = strlen($urlhash); #将加密后的串分成4段,每段4字节,对每段进行计算,一共可以生成四组短连接 for ($i = 0; $i < 4; $i++) { $urlhash_piece = substr($urlhash, $i * $len / 4, $len / 4); #将分段的位与0x3fffffff做位与,0x3fffffff表示二进制数的30个1,即30位以后的加密串都归零 $hex = hexdec($urlhash_piece) & 0x3fffffff; #此处需要用到hexdec()将16进制字符串转为10进制数值型,否则运算会不正常 $short_url = "https://www.cnblogs.com/"; #生成6位短连接 for ($j = 0; $j < 6; $j++) { #将得到的值与0x0000003d,3d为61,即charset的坐标最大值 $short_url .= self::$charset[$hex & 0x0000003d]; #循环完以后将hex右移5位 $hex = $hex >> 5; } $short_url_list[] = $short_url; } return $short_url_list; } }
$url = "https://www.cnblogs.com/wt645631686/p/9720779.html"; $short = Short_Url::short($url); print_r($short);
Array
(
[0] => https://www.cnblogs.com/rPSefD
[1] => https://www.cnblogs.com/KaLKmD
[2] => https://www.cnblogs.com/yrnfXD
[3] => https://www.cnblogs.com/nTabHS
)
//解密,从redis缓存拿 <?php $redis = new Redis(); $redis->connect('localhost',6379); $short = $_GET['s']; $long = $redis->hGet('s',$short); if(!empty($long)){ header("location: ".$long); }else{ header("location: http://test.cn); }
更改nginx配置, 将短链接重定向到处理文件
server{ .... #短链接(http(s)://xxx.com/s/xxx)重定向到 s文件夹下的share.php处理文件 location /s/ { rewrite ^(/s/)(.*)$ $1/share.php?k=$2; } }
当然也可以根目录跳转
location / { if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=$1 last; } }
目的是为了让短链接省去index.php?s=
当然,/index.php
指向了test.cn,所以用一个/s/路径来放,对应的nginx配置写法如下:
location /s/ { if (!-e $request_filename) { rewrite ^/s/(.*)$ /s/index.php?s=$1 last; } }