How can I use .htaccess to modify the functionality of Phil Sturgeon's CodeIgniter REST library so object IDs can be passed in the URL?-Collection of common programming errors
I am using Phil Sturgeon’s REST server for CodeIgniter and want to modify the functionality so I can support URLs like these:
http://api.example.com/users
http://api.example.com/users/1
To get a list of users and a single user respectively, instead of the ones it supports like these:
http://api.example.com/users
http://api.example.com/users?id=1
I read on his blog that this should be possible using mod_rewrite, but have been unable to get this working as expected.
The default CodeIgniter .htaccess looks like this:
RewriteEngine on
RewriteCond $1 !^(index\.php|css|images|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
And I have tried to add my own rules to attempt to achieve this functionality. This is one that I expected to work correctly. It is placed after the activation of the RewriteEngine and before the CodeIgniter rules.
RewriteRule ^users/([0-9+]) /users?id=$1 [NC]
I figured this would then cascade down to the next rule which would route through CodeIgniter and then hit the correct users.php
controller, then the index_get
method (as remapped by the REST Server).
Instead, I get an ‘unknown method’ error – it appears as though CodeIgniter is trying to use the user integer as a function, for example in users/12
it is trying to find the 12()
method in users.php
.
Does anyone know what is going wrong here, or can recommend a solution to this problem?
-
CodeIgniter uses a front controller pattern and supports clean URLs. This means that it should be able to transparently pick up and route requests they way you want. You should be able to set your web server to route all requests to CodeIgniter’s
index.php
and modify it’s configuration file to suit.Edit your
system/application/config/config.php
file and set the index_page variable:$config['index_page'] = '';
. Then, edit your.htaccess
file or your virtual host configuration file in Apache to use something like:# 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: Check out this answer from the author himself, who says that CodeIgniter should pick up either query string or URI segment styles by default.
Edit 2: Ah, I see what you mean. You don’t want to have the query variable name as a URI segment. You can probably fix this by modifying your routes file, such that it sends all queries to a single method on that controller.
Originally posted 2013-11-09 22:46:22.