简体   繁体   中英

.htaccess url to get parameter

I am trying to create a small api, I have a folder named api inside that folder I have index.php and .htaccess What I am trying to do is when I am accessing api/something to transform last parameter to api/?x=something And check in php if function something exist call it if no show 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>

If access api folder it works but if I add api/something no.

If it is Important: the structure of folders is like this: root_website_folder/sub_folder/api When it rewrites 'something' to x=something I get the x to call func name if exist

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);
        }   
    }

You have not added a rule for the api specifically. The following should work:

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] 

This works by excluding /api requests from being captured by the ^(.*)$ rule.

In general you can test your rewrite rules at http://htaccess.mwl.be/ (not affiliated with this, I just find it useful).

You can use the following with RewriteBase directive :

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

This will rewrite /api/something to /api/index.php?x=something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM