2016-06-08 87 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