Apache mod_rewrite – remove extension/add trailing slash/preserve directory structure

apache-2.2mod-rewrite

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.

Best Answer

The regex pattern for first rewrite rule is the reason: ^([^/]+)/$ means any character EXCEPT slash /. Therefore it rejects anything that is located in sub folder.

You should use ^(.+)/$ pattern instead -- this will work for /information/ as well as /categories/category-1/ as well as /categories/category-1/hello-kitten/.

P.S. I would also add the L flag to stop matching further rules:

# add .php file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*[^/])/?$ $1.php [L]