有没有办法重写这个网址?

时间:2013-06-21 16:16:53

标签: .htaccess redirect mod-rewrite url-rewriting

我需要重定向所有这些网址:

www.example.com/blog.php?id=29

这样的网址:

www.example.com/blog/29/this-is-a-blogpost

其中"这是一篇博文"是存储在数据库中的标题。

有没有办法以这种方式重写这些网址?

2 个答案:

答案 0 :(得分:3)

mod_rewrite canot查询你的数据库并从数据库表中提取所提供id的标题。

你需要将id传递给服务器端代码(如php脚本)才能获取&显示标题。

要查看此问题的SO网址:http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url,它会传递ID和标题。因此,您可以拥有友好的网址,例如:

http://www.example.com/blog/29/this-is-a-blogpost

如果你决定按我的建议去做,那么这里是你需要的代码.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
?>

答案 1 :(得分:0)

您要求的内容显然是不可能的:您要重定向到的第二个网址包含原始请求中不存在(已知)的数据。这些数据应该从重定向过程中来到哪里?

另一种方式肯定是 可能并经常完成。

相关问题