有没有办法重写这个URL?

时间:2012-06-12 07:19:29

标签: .htaccess mod-rewrite

我需要重写以下网址:

www.example.com/John.Connor/my-first-post/42

为:

www.example.com/post.php?postid=42&userid=19

表:

USER:
id, name, surname, email, password

POST:
id, title, post, userid

有办法吗?

1 个答案:

答案 0 :(得分:1)

mod_rewrite无法查询您的数据库,因此无法通过.htaccess本身完成。您可以做的是在.htaccess中使用此规则:

通过httpd.conf启用mod_rewrite和.htaccess,然后将此代码放在.htaccess目录下的DOCUMENT_ROOT中:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^[^/]+/[^/]+/([0-9]+)/?$ post.php?postid=42 [L,QSA]

然后在post.php脚本中包含如下代码:

$postid = mysql_real_escape_string($_GET['postid']); 
$userid = mysql_real_escape_string($_GET['userid']);

if (empty($userid)) {
   $userid = mysql_result(mysql_query("SELECT userid FROM POST WHERE id=$posid"), 
              0, "userid");
   // now redirect by appending &userid=49 in the current URL
   header("Location: " . $_SERVER["REQUEST_URI"] . "&userid=" . $userid);
   exit;
}