2016-06-08 64 views
0

我想創建一個很小的API, 我有一個文件夾,我有index.php.htaccess 內一個名爲API文件夾中我所試圖做的是當我訪問api/something到最後一個參數變換到api/?x=something 併爲您在PHP函數是否存在something如果沒有顯示404的.htaccess URL,以獲取參數

<IfModule mod_rewrite.c> 
    RewriteEngine On 

    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-s 
    RewriteRule ^(.*)$ index.php?x=$1 [QSA,NC,L] 

    RewriteCond %{REQUEST_FILENAME} -d 
    RewriteRule ^(.*)$ index.php [QSA,NC,L] 

    RewriteCond %{REQUEST_FILENAME} -s 
    RewriteRule ^(.*)$ index.php [QSA,NC,L] 
</IfModule> 

如果訪問api文件夾,它的工作原理,但如果把它叫做我添加api/something沒有。

如果是很重要的: 文件夾的結構是這樣的: root_website_folder/sub_folder/api 當重寫「東西」給x=something 我得到的x到FUNC調用是否存在

public function init(){ 
     $func = strtolower(trim(str_replace("/", "", $_REQUEST['x']))); 
     var_dump($func); 
     if((int)method_exists($this,$func) > 0){ 
      $this->$func(); 
     }else{ 
      $this->response('', 401); 
     } 
    } 
+0

時發生了什麼你去**/api/something/**? – starkeen

+0

@starkeen它顯示404 – Froxz

+0

您是否可以澄清當您導航到'/ api /?x = something'應該進一步重寫時您期望發生的事情? – apokryfos

回答

1

你有沒有名字特別爲api添加了一條規則。 下面應該工作:

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-s 
RewriteCond %{REQUEST_URI} !^/api 
RewriteRule ^(.*)$ index.php?x=$1 [QSA,NC,L] 

RewriteRule ^api/(.*)$ api/index.php?x=$1 [QSA,NC,L] 

RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^(.*)$ index.php [QSA,NC,L] 

RewriteCond %{REQUEST_FILENAME} -s 
RewriteRule ^(.*)$ index.php [QSA,NC,L] 

這是通過不包括由^(.*)$規則被捕獲/ API請求。

一般來說,你可以測試你的重寫規則http://htaccess.mwl.be/(不隸屬於此,我只是覺得它很有用)。

+0

如果排除uri **/api **,那麼規則將不會將**/api/something **重寫爲** index.php ** – starkeen

+0

@apokryfos謝謝同一件事 – Froxz

+0

@starkeen我一定誤解了這個問題,我認爲這是意圖。 '/ api/something'請求觸發第二條規則。 – apokryfos

0

您可以使用RewriteBase指令如下:

RewriteEngine On 
RewriteBase /api/  
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^(.+)$ index.php?x=$1 [QSA,L] 

這將改寫/API /東西/api/index.php?x=something