【问题标题】:URL Rewriting: "index.php?id=5" to "home.html"URL 重写:“index.php?id=5”到“home.html”
【发布时间】:2010-02-18 22:12:59
【问题描述】:

我正在使用 php 和“template.inc”类开发一个网站。 问题是我想创建一个 mini-cms,允许管理员使用这些 mysql 属性创建一个“html”页面:

Table Name : Page
-----------------
id   :auto-icremented) 
name :varchar

在架构中,如果他创建的页码为“5”,则url为

"ww.mywebsite.com/index.php?id=5".

但是,这不是很美观,所以即使我阅读了很多教程,我也不擅长 url 重写,我想输入名称+“html”来访问页面。

如果我们举个例子

"www.mywebsite.com/index.php?id=5"

如果管理员创建了具有以下值的页面:

id   : 5
name : 'home'

我希望用户可以输入

"www.mywebsite.com/home.html" 

并且没有重定向,因为我希望最后一个 url 必须仍然出现并成为官方 url。

感谢您的回答, 我知道如何将 www.mywebsite.com/index.php?id=5 重写为 www.mywebsite.com/5.html ......但问题是我想首先在和在我的示例中,名称值为“home”(5 =>'home')。 如何使用 url 重写引擎访问我的数据库?

非常感谢, 问候。

【问题讨论】:

    标签: php url-rewriting


    【解决方案1】:

    使用标准 Wordpress 安装中的 .htaccess 文件将所有内容重定向到一个 PHP 文件。像这样的...

    <IfModule mod_rewrite.c>
        RewriteEngine On
        # Base is the URL path of the home directory
        RewriteBase /
        RewriteRule ^$ /index.php [L]
    
        # Skip real files and directories
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule .* /index.php [L]
    </IfModule>
    

    然后使用$_SERVER['REQUEST_URI'] 找出用​​户在寻找什么。如果您想让规则更具体,请修改.*,例如.*\.html

    【讨论】:

    • 感谢您的回答,我知道如何将 www.mywebsite.com/index.php?id=5 重写为 www.mywebsite.com/5.html ...但问题是我首先,要在我的示例之前和在我的示例中获取“名称”值,名称值为“home”(5 =>'home')。如何使用 url 重写引擎访问我的数据库?
    • 您太担心ID了。 URL 重写无法访问您的数据库。 PHP 将需要这样做。因此,您只需重写所有内容,让 PHP 将 REQUEST_URI ("home.html") 取出名称 ("home") 然后在数据库中查找。该名称必须是唯一的。
    【解决方案2】:

    扎卡里亚,

    使用 Renesis 的重写规则后,$_SERVER['REQUEST_URI'] 将等于 'home.html'

    尝试类似:

    <?php
    
    // clean
    $page = mysql_real_escape_string($_SERVER['REQUEST_URI']);
    
    // make query
    $query = sprintf("select Page.* from Page where name = '%s'", $page);
    
    // find page ID
    if($result = mysql_query($query)){
    
      $page = mysql_fetch_assoc($result);
    
      echo "<pre>", print_r($page, true), "</pre>";
    }
    
    ?>
    

    可能的输出

    Array (
      [id]    => 5
      [name]  => 'home.html'
    )
    

    【讨论】:

    • 写完之后,我看到 Zakaria 最终接受了一个答案。我想在这里获得更多 PHP 帮助并没有什么坏处 :)
    • 谢谢,瑞妮丝!你提供了一个很好的起点。我也学会了如何用你的答案跳过真实的文件/目录:)
    • +1 为您解答!这正是我所做的!再次感谢;)
    【解决方案3】:

    为此使用 Apache URL 重写。仅此站点上就有 many many 示例。也可以试试官方Apache rewriting docs

    您需要确保您的数据库强制执行名称的唯一性,否则您将遇到问题。

    编辑

    让您的 index.php 采用 name= 参数而不是 id 参数。您需要确保您的数据库已将名称字段编入索引,这样您就不会为每个页面请求进行表扫描。

    【讨论】:

    • 感谢您的回答,我知道如何将 www.mywebsite.com/index.php?id=5 重写为 www.mywebsite.com/5.html ...但问题是我首先,要在我的示例之前和在我的示例中获取“名称”值,名称值为“home”(5 =>'home')。如何使用 url 重写引擎访问我的数据库?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2013-06-25
    • 2013-09-15
    • 1970-01-01
    相关资源
    最近更新 更多