简体   繁体   中英

php rest api 404 error on url human readable format

I'm trying to write a simple REST API in php. When I try the url http://example.com/jpa/api/src/index.php?controller=arquetipo&method=list I can get response from the api, but I want to call the api in this way: http://example.com/jpa/api/src/index.php/controller/action . The problem is that i got a 404 error on the second url.

This is my entry point

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

...

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
$indexRouterParamController = 5;
$indexRouterParamAction = 6;


if ($uri[$indexRouterParamController] != 'arquetipo') {
    header("HTTP/1.1 404 Not Found");
    exit();
}
else
{
   //response logic here.
}

if I print_r the var $uri, this is what I get when point the browser to http://example.com/jpa/api/src/index.php/arquetipo/list , but when I do a test with postman, I got the 404 error.

Array
(
    [0] => 
    [1] => jpa
    [2] => api
    [3] => src
    [4] => index.php
    [5] => arquetipo
    [6] => list
)

Is this a missing conf for .htaccess or there is something else that I need to know?

As you've already suspected, this is a.htaccess problem.

By default, the web server will map the literal path to the hosting dircectory ie jpa/api/src.

What you will need to achieve what you want is to rewrite the request to format on the fly from your forward/slash/endpoint to the index.php?foo=bar.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ /jpa/api/src/index.php?controller=$1&method=$2 [QSA,NC,L]
</IfModule>

This enables the API to be called as http://example.com/arquetipo/list

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