I'm writing a small php site and I'm trying to structure it properly so that requests are handled centrally and there is a single point of entry to the code.
So I'm using the guide for a single entry point described here: https://thomashunter.name/blog/php-navigation-system-using-single-entry-point/
The mod_rewrite rule works well until you request a directory that actually exists on the server. I've disabled directory indexes but now the accesses behave differently depending on whether there is a trailing slash in the URL or not. With a slash, everything behaves the way I'd like (URL bar is www.example.com/images/
and the server returns a 404 created by my php script) but without a trailing slash the URL is rewritten to www.example.com/index.php?s=images
which looks messy and exposes too much information about the structure of my site.
Seeing how it works with a trailing slash, ideally I want it to work the same way without the trailing slash. Otherwise, if it didn't work in any case, I'd settle for a simple redirect, although I don't like the idea of highlighting the real directories.
My .htaccess
looks like this:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_]+)/?$ index.php?s=$1 [QSA]
Options -Indexes
ErrorDocument 403 index.php
I've also put in a header redirect but the ?s=images
still gets appended to the URL (I am aware this can be written better but I'm experimenting with various combinations at the moment):
if (startsWith($_SERVER['REQUEST_URI'], "/main"))
{
header('Location: '.'/');
exit;
}
else if (startsWith($_SERVER['REQUEST_URI'], "/images"))
{
header('Location: '.'/');
exit;
}
where the definition of startsWith
is (taken from this StackOverflow answer):
function startsWith($haystack, $needle)
{
return $needle === "" || strpos($haystack, $needle) === 0;
}
Finally, I'm looking for a solution that doesn't require copying dummy index.php
s into every directory as that can get difficult to maintain. Any help or guidance will be appreciated.