Search code examples
apache.htaccesspretty-urls

How do I create an .htaccess to serve index if the last node is a directory, else, serve a file?


So, if I have the following URL:

http://www.example.com/Foo/Bar/Drink/

The last node of the URL (in this case, Drink) will be either a directory, in which case I want to serve index.php, or it will be a file named "Drink.php", in which case I want to serve them that file.

http://www.example.com/ would obviously serve index.php.

Both would maintain that "pretty URL" look with the trailing slash.

Is this possible? The site will follow this format consistently and I'm really trying to avoid having to route everything through the main index file.


Solution

  • place this code in .htaccess under the root directory of your site

    Options -MultiViews
    RewriteEngine ON    
    
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule (.+) /$1/index.php [QSA,L]
    
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.+?)/?$ /$1.php [QSA,L]