1

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.phps into every directory as that can get difficult to maintain. Any help or guidance will be appreciated.

Community
  • 1
  • 1
usm
  • 245
  • 2
  • 17
  • You could use mod_rewrite to restrict access to all directories except the ones you want to allow. I believe CodeIgniter does this pretty well. It doesn't allow access to the system or application directories where all the main code is stored. I'd suggest taking a look at the .htaccess for that. – Jonathon Aug 11 '14 at 12:10

1 Answers1

1

you want some sort of routing, either via only apache Routing URLs in PHP or via one of the libraries (apache+php) that are avaliable

(like this one http://www.slimframework.com/)

Community
  • 1
  • 1
birdspider
  • 3,034
  • 1
  • 16
  • 25
  • The linked answer and a web search for 'php routing' led me to this guide: http://www.phpaddiction.com/tags/axial/url-routing-with-php-part-one/ which works for me, even on directories that already exist. – usm Aug 22 '14 at 10:51