【问题标题】:CodeIgniter: Is it possible to remove the controller & function from the URL using routes or .htaccess?CodeIgniter:是否可以使用路由或 .htaccess 从 URL 中删除控制器和函数?
【发布时间】:2011-10-28 23:42:28
【问题描述】:

我有一个由名为“pages”的表组成的数据库。 我有一个名为“站点”的控制器和一个名为“页面”的函数...http://website.com/site/page/page_id

在页面函数中,它当前查找第 3 个 URI 段 (page_id),然后找到并将其与数据库中的页面行匹配并显示行结果。

我的问题是,是否可以将我的 URL 从 http://website.com/site/page/page_id 路由/更改为 http://website.com/page_id。然后显然改变我的函数来找到第一个 URI 段??

我当前的 .htaccess 文件删除了“index.php”,如下所示:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /db

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#‘system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css folders, and the robots.txt file
#Submitted by Michael Radlmaier (mradlmaier)
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don’t have mod_rewrite installed, all 404’s
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>

【问题讨论】:

    标签: php .htaccess codeigniter


    【解决方案1】:

    看看this article。在您的应用程序配置中编辑 routes.php 应该可以解决问题。这样的事情应该可以工作:

    $route['(:any)'] = 'site/page/$1';
    

    但是,如果您使用额外的控制器,则可能需要做更多的工作(我假设“站点”是您的控制器,即 site.php 位于应用程序/控制器中)。

    在代码中,如果您的页面 ID 只是数字,您也可以考虑使用 :num 而不是 :any

    【讨论】:

    • 谢谢!是的,你的权利,我确实有其他控制器和功能仍然需要工作。你能指出我在这方面的正确方向吗?干杯。
    • 如前所述,如果您的页面 ID 是数字,只需使用“(:num)”作为选择器。这样,(非数字)控制器名称将不会匹配和重新路由。
    • 啊,为了简单起见,我放了 page_id,但实际上我使用的是名称的 seo 版本,例如。 page-name 作为选择器.. 还有可能吗?为帮助干杯..
    • 路由按照定义的顺序运行,因此您可能需要为所有控制器创建路由,然后在路由文件末尾添加此路由。
    • 阅读我链接到的文章。您可以使用正则表达式或路由的正确顺序(或两者结合)来过滤应以常规/旧方式处理的某些页面。
    猜你喜欢
    • 2011-09-05
    • 2014-12-16
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2015-03-02
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多