【问题标题】:Use apache mod rewrite with php variable inside page在页面内使用带有 php 变量的 apache mod rewrite
【发布时间】:2015-10-29 18:14:42
【问题描述】:

我通过将 GET 参数传递到 url 来显示数据库中的记录:http://example.com/record?id=2

记录有一个名为“title”的字段,我想用它来重写 url 以显示如下: http://example.com/record/title

例如:http://example.com/record/This-is-the-Record-Title

在页面内部,我有一个变量 $title,它从记录中提取“title”值。如何使用 $title 变量来重写如上例所示的变量?

【问题讨论】:

    标签: php mysql apache mod-rewrite


    【解决方案1】:

    答案有两个:

    1. 设置 mod_rewrite 以将请求拆分为变量(使用搜索 mod_rewrite 主题),并且
    2. 创建反向路由,采用 This-is-the-Record-Title 并将其转换为数字 2

    希望能把你带到你想去的地方。

    【讨论】:

      【解决方案2】:

      由于 mod_rewrite 无法获得有关标题的信息,因此您最好从 PHP 设置重定向。喜欢:

      /*** find out record title here ***/
      $_SESSION['id'] = $_REQUEST['id'];
      header('HTTP/1.1 302 Found');
      header('Location: http://example.com/record/'.$record_title);
      

      id 可以存储在会话变量中,因此您不必反向检索它。更好的是使用经过验证的值,例如从数据库行返回的 id,因为这不容易受到用户端的任何修改。但是,如果用户通过“漂亮链接”访问记录,则必须从标题中查找记录。

      对于 mod_rewrite,你应该设置一个内部重写,所以记录标题而不是实际脚本将显示给用户:

      RewriteEngine  on
      RewriteRule    "^/record/(.*)$"  "/records.php?title=$1" [PT]
      

      【讨论】:

        猜你喜欢
        • 2019-04-30
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        • 2014-01-25
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多