关于使用 PHP 和 .htaccess mod 重定向创建具有动态内容的 SEO 友好 URL 的分步说明。友好的 URL 可以提高您的网站搜索引擎排名。在尝试之前,您必须在 httpd.conf 中启用 mod_rewrite.so 模块。只需几行 PHP 代码即可将标题数据转换为干净的 URL 格式,这很简单。
数据库
示例数据库博客表列 id、title、body 和 url。
CREATE TABLE `blog`
(
`id` INT PRIMARY KEY AUTO_INCREMENT,
`title` TEXT UNIQUE,
`body` TEXT,
`url` TEXT UNIQUE,
);
Publish.php
包含 PHP 代码。将标题文本转换为友好的 url 格式并存储到博客表中。
<?php
include('db.php');
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title = mysql_real_escape_string($_POST['title']);
$body = mysql_real_escape_string($_POST['body']);
$title = htmlentities($title);
$body = htmlentities($body);
$date = date("Y/m/d");
//Title to friendly URL conversion
$newtitle = string_limit_words($title, 6); // First 6 words
$urltitle = preg_replace('/[^a-z0-9]/i', ' ', $newtitle);
$newurltitle = str_replace(" ", "-", $newtitle);
$url = $date . '/' . $newurltitle . '.html'; // Final URL
//Inserting values into my_blog table
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
}
?>
<!--HTML Part-->
<form method="post" action="">
Title:
<input type="text" name="title"/>
Body:
<textarea name="body"></textarea>
<input type="submit" value=" Publish "/>
</form>
Article.php
包含 HTML 和 PHP 代码。显示博客表中的内容。
<?php
include('db.php');
if($_GET['url'])
{
$url =mysql_real_escape_string($_GET['url']);
$url = $url . '.html'; //Friendly URL
$sql = mysql_query("select title,body from blog where url='$url'");
$count = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
$title = $row['title'];
$body = $row['body'];
}
else
{
echo '404 Page.';
}
?>
<!-- HTML Part -->
<body>
<?php
if($count)
{
echo "<h1>$title</h1><div class='body'>$body</div>";
}
else
{
echo "<h1>404 Page.</h1>";
}
?>
</body>
.htaccess
URL 重写文件。将原始 URL 9lessons.info/article.php?url=test.html 重定向到 9lessons.info/test.html
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1