PHP伪静态与短链接

如今,Web服务高速发展的时代,各式各类的门户网站,如新浪http://www.sina.com、腾讯http://www.qq.com,这些网站大家都很容易记住,因为这种名称都是有规则和含义的。如果给你一个http://14.215.177.38,你肯定记不住这个网站是什么,可是我告诉你它就是百度首页。

所以,我们在开发一个网站系统的时候,还是要对链接进行优化的,而我理解的优化类型有伪静态短连接

其实,如果你数据结构学的不错,这个对你来说很容易理解,毕竟它就是一种地址映射的关系。

常识告诉我们,当我们请求一个URL的时候,我们需要附带一些参数才能得到各种动态的效果,而这种附加参数方式,例如www.baidu.com?keywords=http,表示我们使用百度搜索关键字http,这样百度引擎就可以根据参数,返回响应的列表页给用户。 

而,我们想实现所谓地址优化:如

伪静态

用户可以直接访问这样的链接

http://www.baidu.com/http.html  效果和上面是一样的。

短连接

如,一个链接www.baidu.com?name=lisa&age=18,我们可以转化为:www.baidu.com/lisa/18

接下来,我们来一个实战,如何在Apache服务的PHP网站系统实现伪静态和短链接呢?

我们拿到一个链接:http://localhost/index.php/act/search/op/index/cate_id/314

第一步,我们去掉index.php

 配置Apache Rewrite实现

1 <IfModule mod_rewrite.c>
2     RewriteEngine on
3     RewriteCond %{REQUEST_FILENAME} !-d
4     RewriteCond %{REQUEST_FILENAME} !-f
5     RewriteRule ^(.*)html$  /index.php/$1 [QSA,PT,L]
6 </IfModule>

第二步,对链接进行映射和静态处理

 1 #获取请求完整URI地址
 2 $path_info = $_SERVER['REQUEST_URI'];
 3 #截获参数部分
 4 $path_info = substr($path_info,strrpos($path_info,'/')+1);
 5 #过滤?号后面内容
 6 if(strpos($path_info, '?')) {
 7        $path_info = substr($path_info, 0, (int) strpos($path_info, '?'));
 8 }
 9 //去掉伪静态扩展名
10 $path_info = substr($path_info,0,-strlen($this->_rewrite_extname));
11 //根据规则匹配URL
12 $path_info = $this->path_info_function($path_info);
13 
14 #根据路由规则匹配(路由表)
15 private function path_info_function($path_info) {
16         $reg_match_from = array(
17             '/^article-(d+)$/',
18             '/^article_cate-(d+)$/'
19         );
20         $reg_match_to = array(
21             'article-show-article_id-\1',
22             'article-article-ac_id-\1'
23         );
24         return preg_replace($reg_match_from,$reg_match_to,$path_info);
25     }
26 
27 #匹配完成后,得到参数字符串;并对其进行解析,得到参数表
28 $split_array = preg_split($this->_pathinfo_pattern,$path_info);
29 
30 //act,op强制赋值,得到路由
31 $_GET['act'] = isset($split_array[0]) ? $split_array[0] : 'index';
32 $_GET['op'] = isset($split_array[1]) ? $split_array[1] : 'index';

一切搞定。

这样我们就可以得到,一个短链接,并且支持伪静态:http://localhost/search-index-314.html

原文地址:https://www.cnblogs.com/helingfeng/p/5827378.html