The many benefits of .htaccess files

Apache HTTP Server is controlled by a series of directives, which are usually placed inside Apache’s main configuration file. The file is often called httpd.conf or apache2.conf. This configuration file is located in the /etc directory in Linux, and any changes you make to the file, which you must edit as root, will affect all of the server’s websites.

If you only want to change one website, making changes to your Apache configuration file is probably a bad idea. Fortunately, Apache allows users to place hidden files, called .htaccess, in their Web document directories that can also run Apache directives. When .htaccess is enabled on a server, it can be a very powerful tool.

To enable support for .htaccess on your dedicated server, locate the line in your configuration file that reads:

AllowOverride None

and change it to:

AllowOverride All

Here are a few .htaccess examples:

Access Control. Simply put, you can deny visitors from accessing certain parts of your site. You might have a directory that contains scripts. Your server runs the scripts, but you do not want outsiders to have access to them. Put the following line in an .htaccess file in that directory:

deny from all

Custom Error Documents. This is very useful if you want users to not feel lost when they reach the dreaded 404 Not Found, which is a plain white page with information about Apache and your OS. To create custom error documents, edit your root document .htaccess file and enter something like:

ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html

Then, create the files in the directory you have specified, making custom error documents. You can be as creative as you want.

Mod rewrite. With the Apache rewrite module, you can change the way URLs appear to web browsers and search engines.

For example, to change a URL like to something more friendly, put the following lines in an .htaccess file:

RewriteEngine on
RewriteRule ^([^/.]+).html$ index.php?page=$1 [L]

Your URL will now appear as:

There are numerous other uses for .htaccess, and Apache documentation contains a list of all available directives. Best of all, if you ever need to undo something, simply remove whatever directive you have set in place without having to restart Apache. Enjoy!