【发布时间】:2012-10-26 11:57:29
【问题描述】:
我想让我的链接 SEO。在我开始之前,链接看起来像这样:
http://www.domain.tld/index.php?page=blog
我的目标是将其更改为:http://www.domain.tld/blog。现在可以了。
我把 htaccess 改成了这个:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)$
RewriteRule ^index\.php$ /%1? [R=301,L]
RewriteRule ^blog/(\d+)-([\w-]+)$ index.php?page=single_news&id=$1&headline=$2
现在我想更改任何博客条目标题的 URI。他们看起来像这样:http://www.domain.tld/index.php?page=single_news&id=2&headline=This%20Is%20A%20Headline
我想让它们看起来像这样:http://www.domain.tld/blog/2-this-is-a-headline
我正在 div 类“news_headline”中生成我的标题链接(见下文)。
<div id="main">
<?php
$query = "SELECT `id`, `headline`, `writer`, `content`, DATE_FORMAT(date,\"%d. %M %Y\") AS `date` FROM `blog` ORDER BY `id` DESC";
$news_resource = mysql_query($query) or die(mysql_error());
?>
<?php
$all_news = array();
$five_news = array();
for($i = 0; $news = mysql_fetch_object($news_resource); $i++){
if($i < 5){
$five_news[] = $news;
}
$all_news[] = $news;
}
?>
<?php foreach($five_news as $news)
{ ?>
<div class="news_bg">
<div class="news_headline"><a href="blog/<?php echo $news->id; ?>-<?php echo $news->headline; ?>"><?php echo $news->headline; ?></a></div>
<div class="news_infoline_top"><?php echo $news->date; ?> · <?php echo $news->writer; ?></div>
<div class="news_text"><?php echo $news->content; ?></div>
</div>
<?php } ?>
</div>
使用我的 htaccess(见上文),链接现在是这样的:
http://www.domain.tld/blog/2-This Is A Headline
我已经得到了这方面的帮助,一个好人给了我这个 code-sn-ps 以使链接看起来像我想要的那样,但我不知道如何使用它们:
$urititle = strtolower(preg_replace('/[^\w-]+/','-', $title));
和
$_GET['headline'] != $urititle
我迷路了。
【问题讨论】:
-
只是一些注释:5 新闻是
LIMIT 5 OFFSET 0in SQL。直接从数据库中查询。然后是一个小错误:您没有从数据库中查询title,而是headline。修复它。您需要在循环中做的下一件事是将标题转换为 "slug",您应该将其放入它自己的函数中(例如slugify($news->title))。 -
你的问题到底是什么?!
-
…或者你只是使用一些现有的功能来做到这一点,例如Textpatterns
dumbDown()函数,它“将字符串转译为 ASCII”。见:textpattern.googlecode.com/svn/development/4.x/textpattern/lib/… -
@SalmanA 我如何获得这样的链接?
http://www.domain.tld/blog/2-this-is-a-headline -
Please, don't use
mysql_*functions in new code。它们不再维护,deprecation process 已开始使用。看到red box?了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial.
标签: php regex clean-urls