Apache mod_rewrite - remove extension/add trailing slash/preserve directory structure
- by Henry Wrinkler
I am currently using the following .htaccess file to remove the .php extension from my files and add a trailing slash to all URLs:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php
# Forces a trailing slash to be added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
This is working great, however, when I have a php file in a directory, and I want to serve that file from a directory I get a 404 error. Is there a way to do this with 1 .htaccess file in the root. I really don't want to remember to put a .htaccess file in each directory.
Right now
www.myexample.com/information/
Serves /information.php. Great! However
www.myexample.com/categories/category-1/
this throws a 404 even though the file /categories/category-1.php does exist. I would like to modify my .htaccess file so this serves /categories/category-1.php.