.htaccess url获取参数

时间:2016-06-08 07:53:25

标签: apache .htaccess mod-rewrite

我正在尝试创建一个小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);
        }   
    }

2 个答案:

答案 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

相关问题