I am having issues getting my site to rewrite sub-directory locations back to my public/index.php.
Here is my file structure (simple version):
public -> index.html and .htaccess
private -> views -> my viewable .php files
-> src -> router.php (does the routing
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php [QSA,L]
index.php
<body>
<?php
router();
?>
</body>
router.php
function router()
{
$request = trim(strtolower(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$fileName = PRIVATE_PATH . "/views/" . $request . ".php";
if ($request == "/") { // * WHERE TO GO FOR THE 'HOME' PAGE * //
require_once(PRIVATE_PATH . "/views/home.php"); // ? CAN CHANGE THIS FROM 'home.php' TO OTHER FILE NAME AS DESIRED ? //
} elseif (file_exists($fileName)) { // * LINKS WILL HAVE THE SAME LOCATION AS THE FILENAME (SANS THE .PHP) * //
require_once($fileName);
} else { // * CATCH ALL FOR PAGE NOT FOUND - 404 ERROR * //
http_response_code(404);
require_once(PRIVATE_PATH . "/views/404.php");
}
}
I've read numerous SO pages: Redirect all to index.php using htaccess RewriteRule in sub folder .htaccess URL Rewrite to Subdirectory htaccess rewrite rule for subfolder (nice url)
I'd prefer not to have it rewrite (visably) as a $_GET RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
I am using https://www.taniarascia.com/the-simplest-php-router/ as my base to do this - I added one of the comment's suggestions --
function getBaseURI()
{
$basePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
// Get the current Request URI and remove rewrite base path from it
// (= allows one to run the router in a sub folder)
$uri = substr(rawurldecode($_SERVER['REQUEST_URI']), strlen($basePath));
// Don't take query params into account on the URL
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
// Remove trailing slash + enforce a slash at the start
return '/' . trim($uri, '/');
}
$request = getBaseURI();
It would pull the proper file; however, my index.php file's links such as <script src='./assets/jquery363.min.js'></script>
started trying to pull from the sub-directories...
e.g.: If I put localhost/zero/one/two it would pull from views/zero/one/two.php but I would get a console error for unable to find jquery at localhost/zero/one/assets/jquery363.min.js.
Getting the information to pull from views (with sub-directories) is the easy part. I'm having trouble with my index file's linkages IF a sub-directory is used.
Per a comment suggestion, I tried turning my .htaccess into:
RewriteEngine on
RewriteRule ^.*$ index.php [QSA,L]