Sunday, January 31, 2010

Hiding page extensions

.htaccess files are a wonderful thing, and incredibly powerful, ignoring the bad experience I had with them on my current web host (fortunately, this project is hosted by another web host, and everything runs perfectly with them :)), and Apache's mod_rewrite module does exactly what we need.

There are a bunch of reasons you'd want to do this, mainly:

* it looks cleaner and easier to read and remember
* by using search-engine–friendly URLs, you're Google PageRank will increase and will increase your website's findability
* it makes your website environment-independent, so if you ever decide to change the technology your site uses, everything would appear seamless to your visitors.

In this case, we're using PHP files, but you can change it to whatever type of file you're using, be it .html, .asp, .cfm, or anything else, as long as they're all the same type. (If you want to do this for multiple file types, just copy lines 2–4 and apply the same technique accordingly.)

Open your text editor and create a file called ".htaccess" with the following code in it, and upload it to your site's root directory (Note: On Unix and unix-like operating systems, files that start with a dot are hidden files, so you may not be able to see the file after you save it. To get around this, omit the preceding dot when naming the file, and then rename the file back to ".htaccess" after you have uploaded it to your webserver):


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

(adapted from the Apache mailing list)

Using this code, instead of having to type in http://mysite.com/contact.php, you only need to enter http://mysite.com/contact to access that page. And the best part is, you can still access the page with .php on the end of it, so no old incoming links or bookmarks become orphaned as a result of this, and everyone is happy. x

No comments: