$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs) ){
echo "<a href='/Test/html/news_$row[id].html'>$row[title]</a><br>";
}
?>
比如生成了<a href='/Test/html/news_3.html'>php静态页实现</a>
当点击链接发出对 http://localhost/Test/html/news_3.html 的请求时
Apache将会判断 news_3.html 是否存在,由 .htaccess中的第三句
RewriteCond %{REQUEST_FILENAME} !-s
实现:
RewriteCond 是“定向重写发生条件”。REQUEST_FILENAME 这个参数是“客户端请求的文件名”
'-s' (是一个非空的常规文件[size]) 测试指定文件是否存在而且是一个尺寸大于0的常规的文件. !表示匹配条件的反转。
所以 RewriteCond 这句就表示当请求链接不存在时 执行下面的 RewriteRule 规则。
所以当请求的news_3.html 不存在时会重写地址让 getnews.php?id=3 来处理(否则如果news_3.html 存在则直接就加载该html文件)。
getnews.php ===================>功能:判断参数传输的完整性,并调用相应文件生成html文件。
<?php
$id =$_GET['id'];
$root =& $_SERVER['DOCUMENT_ROOT'];
$filename = "news_".$id.".html";
$file = $root."/Test/html/".$filename;
ob_start();
include($root."/Test/newsDetail.php");
file_put_contents($file,ob_get_contents());
ob_end_flush();
?>
newsDetail.php ====================> 从数据库中读取数据,产生新闻内容,内容被getnews.php捕获
<?php
header("Content-Type:text/html; charset=gbk");
if( isset($_GET['id']) ){
$id = & $_GET['id'];
}else{
header("Location: http://127.0.0.1/lean/Test/html/news_failed.html");
exit();
}
mysql_connect("localhost","root","");
mysql_query('SET NAMES gbk');
mysql_select_db("test");
$id =$_GET['id'];
$sql = "Select `news` FROM `arc` Where `id`=$id";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs) ){
echo $row['news'];
}
?>
这样将会在/Test/html 目录下产生以 news_文章ID.html 命名的html文件。
PS: 一开始在判断是否存在相应html页面时采用的是 php 内置的 file_exists() 判断,而不用Apache的 RewriteCond,也即没有 RewriteCond %{REQUEST_FILENAME} !-s。看似可行,但结果会产生“循环重定向”的问题。
当news_3.html 不存在时 我们需要用 getnews.php生成news_3.html ,生成完毕后需要转向到 news_3.html ,于是又形成了一次请求mod_rewrite又启动把 news_3.html重写为 getnews.php?id=3 这就形成了死循环了。所以把文件存在性的判断交给 RewriteCond ,指定的html文件不存在时才启用重写规则。这样循环重定向的问题就没有了。







