2012-07-24 48 views
0

我使用菲爾鱘魚的REST服務器笨和要修改的功能,這樣我就可以支持URL這樣的:如何使用.htaccess修改Phil Sturgeon的CodeIgniter REST庫的功能,以便可以在URL中傳遞對象ID?

http://api.example.com/users 
http://api.example.com/users/1 

分別獲得用戶的列表和單個用戶,而不是那些支持像這樣的:

http://api.example.com/users 
http://api.example.com/users?id=1 

我看到他blog that this should be possible using mod_rewrite,但一直未能得到這個工作預期。

默認笨的.htaccess看起來是這樣的:

RewriteEngine on 

RewriteCond $1 !^(index\.php|css|images|js|robots\.txt) 
RewriteRule ^(.*)$ /index.php/$1 [L] 

我試圖加入我自己的規則來嘗試實現這一功能。這是我期望正確工作的一個。它位於RewriteEngine激活之後和CodeIgniter規則之前。

RewriteRule ^users/([0-9+]) /users?id=$1 [NC] 

我想通那麼這將級聯到下一個規則,將通過笨,然後打的路線正確users.php控制器,那麼index_get方法(通過REST服務器作爲重新映射)。

相反,我得到一個「未知的方法」的錯誤 - 它看起來好像笨試圖使用用戶整數作爲函數,例如在users/12它試圖找到users.php12()方法。

有沒有人知道這裏出了什麼問題,或者可以推薦解決這個問題?

+0

不要以爲這是你的問題,但是你在你的反向引用中缺少** $ **:'RewriteRule^users /([0-9 +])/ users?id = $ 1 [NC]' – 2012-07-24 06:54:46

+0

對不起,我的壞 - 從我的.htaccess文件複製時發生意外。更新了問題 - 謝謝! – Dwight 2012-07-24 07:07:06

+0

Phils庫支持像你演示的URL ..'site.com/users/1/format/json/X-API-KEY/foobar'只需啓用像@ JoshuaK的答案那樣的漂亮url即可。 – gorelative 2012-07-24 13:17:49

回答

1

CodeIgniter使用前端控制器模式並支持乾淨的URL。這意味着它應該能夠以他們想要的方式透明地提取和路由請求。您應該能夠設置您的Web服務器將所有請求路由到CodeIgniter的index.php並修改其配置文件以適應。

編輯您的system/application/config/config.php文件並設置index_page變量:$config['index_page'] = '';。然後,編輯.htaccess文件或虛擬主機配置文件中的Apache使用類似:

# 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] 

編輯:退房this answer從作者自己,誰說,笨應該拿起無論是查詢字符串或URI段樣式默認情況下。

編輯2:啊,我明白你的意思了。您不希望將查詢變量名稱作爲URI段。您可以通過修改路由文件來解決此問題,以便將所有查詢發送到該控制器上的單個方法。

+0

是的,CodeIgniter路由器工作正常。出現此問題的原因是REST服務器使用路由器的方式有點不同 - 與「索引」功能相反,它將路由到「index_get」或「index_put」。取決於請求方法。 我需要在URL到達CodeIgniter之前重寫URL,以便CodeIgniter能夠正確處理它們。 – Dwight 2012-07-24 07:33:21

+0

編輯我的答案(x2)。這有幫助嗎? – jmkeyes 2012-07-24 07:38:57

相關問題