Redirect all routes of a REST API to the index

1

Hello, I happen to be creating a PHP REST API and I do not want to use a framework  but I have the following problem

I want to create a request by the GET method in which I send the ID of a product to look for it in the database.

That is:

http://localhost/ws_php/productos/1

The problem is that I implemented a .htaccess so that all the requests reach the index.php with the following code that I found on the web

RewriteEngine On
#RewriteRule ^([^/]*)/([^/]*)$ index.php?url=$1&username=$2 [L]
RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA]

when I print the variable $_GET['url']; to find the ID that I sent, it only shows up to "products" without the ID

PHP code

<?php  
    require_once('db.php');
    if ($_SERVER['REQUEST_METHOD']=="GET"){
        $var = $_GET['url'];
        print_r($var);
    }else if($_SERVER['REQUEST_METHOD']=="POST"){
        echo" POST METHOD ";
    }else{
         http_response_code(405);
    }
?>

All requests go to the index except those that point to the image folder

localhost/ws_php/img/miimagen.jpg
    
asked by Wilfredo Aleman 27.03.2018 в 14:03
source

1 answer

2

The regular expression ^([^/]+)/? matches only the first few characters other than a / .

If we search that all the routes that do not exist go to the index, even if they are multiple folders:

RewriteEngine On

# Si la ruta no es un archivo existente, ni una carpeta
# Reescribir al index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ index.php?url=$1 [L,QSA]

If still, all the routes, even existing ones (images for example) have to go to the index, we create two rules: one for when the index is accessed, that does not process more rules; another so that all the rest go to the index.

RewriteEngine On

# Si va al index, que no haga nada
RewriteRule ^index\.php$ - [L,NC]

# Y acá podemos agregar otras excepciones, por ejemplo la carpeta /img
RewriteRule ^img(?:/|$) - [L,NC]


# Reescribir al index todo el resto
RewriteRule ^(.+?)/?$ index.php?url=$1 [L,QSA]
    
answered by 27.03.2018 / 14:20
source