.htaccess front controller mod rewrite trouble

2019-08-26 09:51发布

问题:

I know this should be simple but I'm having a hard time writing the .htaccess rule for my front controller.

The /themes/ folder contains all my css/js/images etc so I don't want them to pass though my controller

The .htaccess file is in the root of the /myadminarea/ folder.

The root of the site (below '/myadminarea' on '/' has NO .htacess file)

Inside the front controller I look at the URL and then include the file directly - however I want to be quite forgiving with the Urls I accept..

If the url is for a specific file I want it to pass though the front controller

If the url is for a directory (trailing forward slash) I want to assume they are looking for index.php within that folder

The below rule works for urls like this

mydomain.com/myadminarea/mysection/action/ 
(loads mydomain.com/myadminarea/mysection/action/index.php via the front controller)

but falls over on urls like this -

mydomain.com/myadminarea/mysection/action/index.php

that contain a filename (it doesn't use the front controller but just loads the file directly) - I know that the !-f excludes the rewrite rule for files, but I've tried every combination I can think of and the below at least works for urls without filenames. When I try to route EVERY request (except those to the themes folder) I get a server configuration error (500)

This is my rule

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^(themes)/ /myadminarea/index.php [NC,L]

edit:

Added Condensed front controller

// what page is actually being requested?
$uri = explode("/", $_SERVER["REQUEST_URI"]);
//lose the first element and add index.php the last one if it is blank
array_shift($uri);
if (end($uri) == ''){
    array_pop($uri);
    $uri[] = 'index.php';
}

$page_requested = implode('/', $uri);
if ($page_requested == 'myadminarea/index.php'){
    $page_requested = false;
}

includePage($page_requested);

function includePage($page_requested){
    if ($page_requested && file_exists(BASE_FILE_PATH . $page_requested) && is_file(BASE_FILE_PATH . $page_requested)){
        include(BASE_FILE_PATH . $page_requested);
    } else {
        echo $page_requested;
    }
}

回答1:

The leading slash in my rewrite rule was killing me...

RewriteRule !^themes/* myadminarea/index.php [L,QSA]

NOT

RewriteRule !^themes/* /myadminarea/index.php [L,QSA]