Rewriting files to directories with Mod_Rewrite
Published on August 14th, 2009
Let’s say you have all your pages in flat files in the same directory. In this example the files have .php extensions but they could be any kind of files. For instance:
lorem.php lorem-ipsum.php lorem-ipsum-dolor.php
These files end up looking like this in your browsers address bar:
www.domain.com/lorem.php www.domain.com/lorem-ipsum.php www.domain.com/lorem-ipsum-dolor.php
Let’s take these file names and turn them in to directories, this makes URI guessing easier (no file extensions) and some would say it would look better. These files showing up like directories would look like this:
www.domain.com/lorem/ www.domain.com/lorem/ipsum/ www.domain.com/lorem/ipsum/dolor/
If you would do this by hand it would mean making directories by hand and placing the files in those directories. Depending of the amount of pages in your website this could mean a lot of work.
Rewriting to directories
Luckily there’s and easy method to replace URI’s with mod_rewrite. The following lines in your .htaccess document will do the trick:
<IfModule mod_rewrite.c> Options +FollowSymLinks Options +Indexes RewriteEngine On RewriteBase / RewriteRule ^([0-9A-Za-z]*)/$ http://www.domain.com/$1.php RewriteRule ^([0-9A-Za-z]*)/([0-9A-Za-z]*)/$ http://www.domain.com/$1-$2.php RewriteRule ^([0-9A-Za-z]*)/([0-9A-Za-z]*)/([0-9A-Za-z]*)/$ http://www.domain.com/$1-$2-$3.php [L] </IfModule>
Make sure to change the .php extension in this code to the extension of your choice. You could also use multiple rewrite rules for multiple extensions.
Maximum directory depth
This rewrite takes up to three words per file name into account. Longer file names such as lorem-ipsum-dolor-sit.php would be rendered without any rewriting. A fourth (or more) directory rewrite could be handled by adding extra lines for each word/directory:
RewriteRule ^([0-9A-Za-z]*)/([0-9A-Za-z]*)/([0-9A-Za-z]*)/([0-9A-Za-z]*)/$ http://www.domain.com
Some SEO’s would argue that file names carry more weight (in search engine algorithms) then directory’s. Other SEO’s claim that the directory carries more weight, especially without the use of a file name. Both arguments sound valid but there’s no real way to say which is true.
However, it’s a good idea too use a maximum depth of three directory’s so you don’t spread the keyword focus over too many words.