Friday, March 8, 2013

How to remove file extension via .htaccess

If you want to "tidy up" you site, this is a nifty little tip.
BUT - it should really be done for new sites, else you will have to add 301 redirects.


Further, if you don't know what htaccess is, you probably shouldn't be doing anything like this.

EG for PHP

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

The .htaccess file needs to go in the same directory as the file as it works from the top down. If you have the .htaccess in a certain directory, it will affect any other sub files/folders within it.

To add / at the end

Replace the last line of code:
RewriteRule ^(.*)$ $1.php

With these lines:
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]

NOTE: You should use absolute paths, rather than a relative ones for images, CSS etc.
Also, avoid creating an edge case from using folder names the same as file names within it... else you will need to add an exception.