1

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

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

像这样的网址:

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

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

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

4

2 回答 2

3

那么 mod_rewrite 无法查询您的数据库并从数据库表中提取提供的 id 的标题。

您需要将 id 传递给服务器端代码(如 php 脚本)以获取和显示标题。

例如,查看这个问题的 SO URL:http://stackoverflow.com/questions/17239887/is-there-a-way-to-rewrite-this-url它在哪里传递 id 和 title。所以你可以有友好的 URL,比如:

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
?>
于 2013-06-21T16:28:07.910 回答
0

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

反过来肯定可能的,而且经常这样做。

于 2013-06-21T16:25:51.473 回答