2013-07-03 126 views
1

設置子目錄URL重寫PHP

我有我的文件結構設置爲這樣:

/root 
    | 
    /api 
     | 
     /Slim PHP framework 
     index.php 
    | 
    index.php 

的修身目錄內index.php包含從Mongo數據庫檢索JSON數據所需的路線。例如。

$app->get('/users(/:id)', function($id = null) use ($app, $collection) { 
    /* Do mongo search and echo json_encoded data back */ 
}); 

我有一個.htaccess文件包含:其從文件中刪除根目錄下的.php擴展。

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php` 

問題

我可以使用URL訪問我的JSON數據:http://localhost:8888/root/api/index.php/users。 但是,我想要做的是使用url訪問數據:http://localhost:8888/root/api/users

+0

您的JSON數據網址中發生了哪些變化,並保持靜態?你會一直在調用index.php嗎?它總是以'/ users'結尾嗎? –

+0

index.php將始終存在,因爲它是運行路由的文件。網址會根據需要的數據而變化,例如'/ api/index.php/users/1'上的GET請求將獲得ID爲#1的用戶,並且沒有##參數將檢索所有用戶。另外,未來,我可能會以其他方式結束,或者堅持使用'api/data /'來檢索所有內容。所以對於這種情況,只是'/ users /'會感謝 – ashley

回答

3

如果我理解正確,那麼這是怎麼回事?

RewriteRule ^api/users/(.*)$ /root/api/index.php/users/$1 [L] 
RewriteRule ^api/users$ /root/api/index.php/users [L] 

這應該允許這個URL。

http://localhost:8888/api/users/1 

,它將使這也

http://localhost:8888/api/users 

編輯:

這應該讓你的用戶後添加一個數字。還縮短了URL,因此您不必在URL中包含根目錄。

+0

不行,我很害怕。是否有可能取代'/ api/users',做'/ api/v1/users',並使用佔位符作爲index.php部分? – ashley

+0

究竟是行不通的?你有錯誤嗎?或者什麼都沒有發生......看我的更新 –

+0

謝謝!這是完美的,對於遲到的回覆感到抱歉 – ashley

1

假設,你.htacces位於網站根目錄「/」

​​3210

這將重定向注意

http://localhost/root/api/users/1 => http://localhost/root/api/index.php/users/1 
http://localhost/root/api/data/20 => http://localhost/root/api/index.php/data/20 
0

一兩件事,規則的順序也很重要,因此,如果您需要重寫/重定向http://example.com/usershttp://example.com/users/http://example.com/userinfo/而同時重寫http://example.com/users/unamehttp://example.com/scripts/script.php?id=uname那麼這一個應該工作:RewriteEngine on

RewriteEngine on 
RewriteRule ^users/$ /userinfo/ [L] 
RewriteRule ^users/(.*)$ /scripts/script.php?id=$1 [L] 
RewriteRule ^users$ /userinfo/ [L] 

可以有一個更好的解決方案,少一行,但這對我很有用。