phpapache.htaccessurlddev

How to redirect in htaccess without blocking php api?


I have an index.php file which is located in the root directory. This outputs either HTML or JSON, depending on the URL:

<?php
    require_once('./../private/Router.php');
    new Router();
?>

<html lang=“en”>
...

The Router looks like that:

<?php

require_once('Api.php');

class Router
{
    public function __construct()
    {
        $uri = $_SERVER['REQUEST_URI'];
        $method = $_SERVER['REQUEST_METHOD'];

        if (preg_match('/^\/api\//', $uri)) {
            $endpoint = str_replace('/api/', '', $uri);
            $api = new Api();
            $data = null;

            switch ($endpoint) {
                case 'players':
                    $data = $api->getPlayers();
                    break;
            }

            if ($data != null) {
                $api->sendResponse($data);
            } else {
                $api->sendResponse(['error' => 'Endpoint not found'], 404);
            }
            
            exit;
        }
    }
}

My htaccess redirected successfully for all scenarios, except when /asdasd/asdas is entered, for example. The content from my root page shows but it throws an error at "<html...". "Uncaught SyntaxError: Unexpected token '<'" but its working if call any other url, just not with a slash in it. How do I fix this?

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ / [QSA,L]
</IfModule>

Cases tested:

<domain>
<domain>/api/players
<domain>/api/players2
<domain>/asd (Possible to remove "asd" after redirect?)
<domain>/asd.php (Possible to remove "asd.php" after redirect?)
<domain>/asd/asd (PROBLEM!)

Solution

  • It was interesting to note that it was only problematic for paths with a slash. In the .htaccess it was defined that all requests are redirected, which actually worked, but in the index.php the path to the files such as Javascript, CSS etc. was defined as follow:

    ./scripts/main.js
    ./styles/main.css
    

    The behavior is interesting because everything worked with all calls that were either forwarded by the .htaccess or found directly, but not with this other case. To fix this, only the dot at the beginning of the implementation could be removed.

    /scripts/main.js
    /styles/main.css
    

    Based on the slash in the URL, the request assumed to be in a different directory, which is why the files threw errors and the syntax was assumed incorrectly.