我正在为CodeIgniter使用Phil Sturgeon的REST服务器,并希望修改功能,以便支持以下URL:
http://api.example.com/users
http://api.example.com/users/1
要分别获得用户和单个用户的列表,而不是它支持的用户,如
http://api.example.com/users
http://api.example.com/users?id=1
我在他的博客上读到,使用mod_rewrite应该可以实现这一点,但无法按预期实现。
默认的CodeIgniter.htaccess如下所示:
RewriteEngine on
RewriteCond $1 !^(index'.php|css|images|js|robots'.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
我尝试添加自己的规则来尝试实现这一功能。这是我期望正确工作的一个。它位于"重写引擎"激活之后,CodeIgniter规则之前。
RewriteRule ^users/([0-9+]) /users?id=$1 [NC]
我认为这将级联到下一个规则,该规则将通过CodeIgniter路由,然后到达正确的users.php
控制器,然后是index_get
方法(由REST服务器重新映射)。
相反,我得到了一个"未知方法"错误——看起来CodeIgniter试图将用户整数用作函数,例如在users/12
中,它试图在users.php
中找到12()
方法。
有人知道这里出了什么问题吗,或者可以推荐解决这个问题的方法吗?
CodeIgniter使用前端控制器模式并支持干净的URL。这意味着它应该能够以您想要的方式透明地接收和路由请求。您应该能够将web服务器设置为将所有请求路由到CodeIgniter的index.php
,并根据需要修改其配置文件。
编辑system/application/config/config.php
文件并设置index_page变量:$config['index_page'] = '';
。然后,在Apache中编辑.htaccess
文件或虚拟主机配置文件,以使用以下内容:
# Turn on the rewriting engine.
RewriteEngine On
# Default rewrite base to /
RewriteBase /
# Rewrite if the request URI begins with "system":
RewriteCond %{REQUEST_FILENAME} ^system
RewriteRule ^(.*)$ index.php/$1 [NC,L]
# Or if it points at a file or directory that does not exist:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Also rewrite it to the front controller.
RewriteRule ^(.*)$ index.php/$1 [NC,L]
编辑:看看作者自己的回答,他说CodeIgniter默认情况下应该选择查询字符串或URI段样式。
编辑2:啊,我明白你的意思了。您不希望将查询变量名作为URI段。您可以通过修改路由文件来解决此问题,使其将所有查询发送到该控制器上的单个方法。