Php 如何使用.htaccess修改Phil Sturgeon';s CodeIgniter REST库,以便可以在URL中传递对象ID?
我正在使用Phil Sturgeon的REST server for CodeIgniter,并希望修改其功能,以便支持如下URL:Php 如何使用.htaccess修改Phil Sturgeon';s CodeIgniter REST库,以便可以在URL中传递对象ID?,php,.htaccess,codeigniter,rest,Php,.htaccess,Codeigniter,Rest,我正在使用Phil Sturgeon的REST server for CodeIgniter,并希望修改其功能,以便支持如下URL: http://api.example.com/users http://api.example.com/users/1 http://api.example.com/users http://api.example.com/users?id=1 要分别获取用户列表和单个用户,而不是它支持的用户列表,请执行以下操作: http://api.example.com
http://api.example.com/users
http://api.example.com/users/1
http://api.example.com/users
http://api.example.com/users?id=1
要分别获取用户列表和单个用户,而不是它支持的用户列表,请执行以下操作:
http://api.example.com/users
http://api.example.com/users/1
http://api.example.com/users
http://api.example.com/users?id=1
我读了他的文章,但一直未能如期完成
默认的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\u get
方法(由REST服务器重新映射)
相反,我得到了一个“unknown method”错误-看起来好像CodeIgniter试图将用户整数用作函数,例如在users/12
中,它试图在users.php
中找到12()
方法
有人知道这里出了什么问题,或者可以推荐解决方案吗?CodeIgniter使用前端控制器模式并支持干净的URL。这意味着它应该能够透明地按照您想要的方式接收和路由请求。您应该能够将web服务器设置为将所有请求路由到CodeIgniter的
index.php
,并修改其配置文件以适应需要
编辑system/application/config/config.php
文件并设置index\u page变量:$config['index\u 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]
Edit:查看作者本人,他说CodeIgniter应该默认选择查询字符串或URI段样式
编辑2:啊,我明白你的意思了。您不希望将查询变量名作为URI段。您可能可以通过修改路由文件来解决此问题,这样它会将所有查询发送到该控制器上的单个方法。不要认为这是您的问题,但您的反向引用中缺少$:RewriteRule^users/([0-9+])/users?id=$1[NC]
对不起,我的问题-从.htaccess文件复制时发生了意外。更新了问题-谢谢!Phils库支持您演示的URLsite.com/users/1/format/json/X-API-KEY/foobar
只需启用类似@JoshuaK答案的漂亮URL即可。是的,CodeIgniter路由器工作正常。出现此问题的原因是REST服务器使用路由器的方式有点不同,它将路由到index\u get
或index\u put
等功能,而不是index
功能。取决于请求方法。我需要在它们到达CodeIgniter之前重写URL,以便CodeIgniter能够正确处理它们。这有用吗?