我需要重定向所有URL这样的:
I need to redirect all urls like these:
www.example.com/blog.php?id=29
要这样的网址:
www.example.com/blog/29/this-is-a-blogpost
其中,这是一博文是存储在数据库中的标题
Where "This is a blogpost" is the title stored in the database.
有没有办法以这种方式重新编写这些网址?
Is there a way to rewrite these urls in this way ?
好了mod_rewrite canot查询数据库,拉动标题从数据库表中所提供的ID。
Well mod_rewrite canot query your database and pull the title for the provided id from a DB table.
您将需要通过ID到服务器端code(如PHP脚本),以获取和放大器;显示标题。
You'll need to pass id to a server side code (like a php script) in order to fetch & display title.
有关前看SO网址这个问题: http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url
在那里经过两个ID和标题。所以,你可以有友好的URL,如:
For ex look at the SO URL for this question: http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url
where it is passing both id and title. So you can have friendly URLs like:
http://www.example.com/blog/29/this-is-a-blogpost
如果您决定通过我的建议去那么这里就是code,你需要在.htaccess:
If you decide to go by my suggestion then here is the code you will need in .htaccess:
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteRule ^blog/([0-9]+)/([^/]*)/?$ /content.php?id=$1&title=$2 [L,QSA,NC]
然后在你的 content.php
:
<?php
$id = $_GET['id'];
$title = $_GET['title'];
$dbTitle = // get title from Database query using $id
...
if ($title != $dbTitle) {
// redirect with 301 to correct /blog/<id>/<title> page
header ('HTTP/1.1 301 Moved Permanently');
header('Location: /blog/' . $id . '/' . $dbTitle);
exit;
}
// rest of your script
?>