Home : Internet : Server : Apache : Mod Rewrite : Hide File Extensions

Hide File Extensions

Generally speaking, security through obscurity is weak but you still may wish to hide the fact that you are running your site on PHP. Or for SEO purposes, you might wish to use no file extensions at all.

You may have noticed here, I have no file extensions. You can achieve this effect by creating a directory for each page and using an index file. It is a lot easier to use mod_rewrite though.

This code should be placed in the htaccess file in the directory you wish to hide the file extensions for. You can place this in the root of your domain and it will be inherited through all subdirectories.

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteCond %{SCRIPT_FILENAME} !-d
   RewriteRule ^([^\.]+)$ $1.php [NC,L]
<
/IfModule>

The IfModule wrapper ensures we only execute this code if the mod_rewrite module is enabled. See portability notes for more information.

Inside the IfModule, the first three lines are discussed and explained in Start Rewriting (part one). All we are doing is ensuring we are ready to rewrite.

We then have a condition to ensure a real directory has not been requested. If no directory exists, we rewrite all requests for a file with no extension (determined by if we have a . or not) to the corresponding file with .php as the extension.