The Code
Copy the following to a plain text editor and save as .htaccess. Then, via FTP, upload to the root folder of your website (usually called public_html). It will be suitable for most hosting environments, but not all. You can find the website template I’ve also written which contains this .htaccess example here.
<files .htaccess>
order allow,deny
deny from all
</files>
options all -indexes
rewriteengine on
rewritecond %{http_host} ^www\.(.*)$ [nc]
rewriterule ^(.*)$ http://%1/$1 [r=301,l]
rewriterule ^/?(.*/?)index\.(htm|html|php) /$1 [r=301,l]
rewritecond %{request_filename} !-d
rewritecond %{request_filename}\.php -f
rewriterule ^(.*)$ $1.php
errordocument 404 /404
Each Section Explained
A description of the purpose of each section so that you understand better what’s going on and also so that you can remove any bits you don’t need.
<files .htaccess>
order allow,deny
deny from all
</files>
Protects the .htaccess file itself from unauthorized access.
options all -indexes
Disables directory indexes so that no one can snoop the contents of folders on your server.
rewritecond %{http_host} ^www\.(.*)$ [nc]
rewriterule ^(.*)$ http://%1/$1 [r=301,l]
Redirects your site to all non-www. URLs. So, from http://www.example.com/ to http://example.com/.
rewriterule ^/?(.*/?)index\.(htm|html|php) /$1 [r=301,l]
Ensures that your homepage is always reached at the proper http://example.com/ as opposed to http://example.com/index.php.
rewritecond %{request_filename} !-d
rewritecond %{request_filename}\.php -f
rewriterule ^(.*)$ $1.php
Allows for cleaner, friendlier URLs. For example: http://example.com/contact as opposed to http://example.com/contact.php.
errordocument 404 /404
If a visitor types a URL incorrectly, clicked on a link with an error in it, or a page they’re trying to reach no longer exists, instead of seeing a generic error message, can be redirected to a custom error page.
Security
.htaccess is very powerful. You can do a great deal to protect your site from vulnerabilities and spam with it. I highly recommend checking out some of the blacklists Perishable Press has to offer.