【问题标题】:Pretty URL's with CodeIgniter带有 CodeIgniter 的漂亮 URL
【发布时间】:2013-07-09 05:21:51
【问题描述】:

我对 CI 相当陌生,并且一直在尝试如何生成干净的 URL。我之前通过编辑我的 .htaccess 文件完成了这项任务,但没有使用框架。

RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile.php?id=$1 [L]

使用 CI,我尝试了以下方法:

#Get rid of the index.php that's in the URL by default
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile?id=$1 [L]

我知道,默认情况下,URL 中控制器(在本例中为 Profile 控制器)名称后面的值将调用控制器类中具有相同名称的函数。但是,如果在控制器后指定的 URL 中没有值,默认情况下会调用 index 函数。我计划将函数名称留空,以便默认调用索引函数。但是,重写规则不起作用。

有什么想法吗?

【问题讨论】:

  • 只需使用 CI 的路由来处理配置文件 URL 结构。

标签: codeigniter .htaccess mod-rewrite friendly-url


【解决方案1】:

.htaccess 你可以这样做

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile/index/$1 [L]

在重写中你必须提到函数名,无论是索引函数还是其他函数

同样可以使用 CI 路由routes.php

$route['profile/(:any)']    = "profile/index/$1";

现在可以在profile的索引函数中获取参数

function index($id) {
echo $id;
echo $this->uri->segment(3);
//Both will result the same 
}

【讨论】:

  • 这很好用。但是,当我尝试通过使用 $route['users/(:num)/(:num)'] = "users/index/$1/$2"; 添加第二个变量来对此进行扩展时在 routes.php 文件中,当 URL 中缺少第二个变量时,它不起作用。 $2 变量是可选的。它不必在那里。但是,如果它在 URL 中,它应该可以工作。
  • 所以先用单个参数重写routes.php中的两个路由,然后再重写其他
  • 谢谢!效果很好!
猜你喜欢
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2018-04-06
  • 2012-05-07
  • 2013-08-30
  • 2019-02-08
  • 2017-04-16
  • 1970-01-01
相关资源
最近更新 更多