joemidi
joemidi

Reputation: 43

htaccess rewrite to root index if no index file found

I have a site with pre-existing index.php files in certain folders. As part of a push to make the site more dynamic, and routing from a centralised index file I want all subdirs on my site to rewrite to the root index.php if no index(php|htm|html) is found in that dir.

--+ /
  | /index.php
  +--+
  |  + /subdir1
  |
  |--+
     | /subdir2
     + /subdir2/index.php

So that subdir1 will use the root index.php, but subdir2 would use the index.php file that it has in its directory.

I have used a FallbackResource, because thats EXACTLY what I want:

#Use root index.php
FallbackResource /index.php

However, I had found that when I use that, I get the following error message.

Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

So I reverted back to the older:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [NC,QSA,L]

but I'm unsure how to exclude subdirs that already have a index file present.

^!/index\.(php|htm|html)

Something like that?

Upvotes: 1

Views: 1091

Answers (1)

anubhava
anubhava

Reputation: 784998

You can use this rule in root .htaccess:

DirectoryIndex index.html index.htm index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{DOCUMENT_ROOT}/$1/index\.html !-f 
RewriteCond %{DOCUMENT_ROOT}/$1/index\.htm !-f 
RewriteCond %{DOCUMENT_ROOT}/$1/index\.php !-f 
RewriteRule ^(.+?)(?:/[^/]+)?/?$ index.php [L]

Upvotes: 3

Related Questions