我正在尝试创建一个小api,
我在该文件夹中有一个名为api的文件夹index.php
和.htaccess
我要做的是当我访问api/something
以将最后一个参数转换为api/?x=something
时
并检查php是否存在函数something
如果没有显示404则调用它。
<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
什么时候重写一下&#39;到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 :(得分: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/测试重写规则(与此无关,我觉得它很有用)。
答案 1 :(得分:0)
您可以将以下内容与RewriteBase指令一起使用:
RewriteEngine On
RewriteBase /api/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?x=$1 [QSA,L]
这会将 / api / something 重写为 /api/index.php?x=something