.htaccess
.htaccess files are a type of "distributed configuration file", meaning that they provide a way to set configuration options in a distributed manner. Specifically, .htaccess files allow you to set rules (such as access permissions and page redirection) to individual folders within a website or server directory. When a .htaccess file is placed in a directory, the defined rules apply to that directory and all of its sub-directories.
Here are some of the things htaccess can do:
- Password-protect directories
- Redirect URLs
- Restrict access based on IP, referrer, etc.
- Enable SSI
- Define custom error documents (e.g. Error 404)
- Change the default directory index page (e.g. index.html, index.php)
- Define MIME types
- Prevent hotlinking (e.g. images)
Notes about .htaccess
- The period (.) is supposed to be there at the start of the file name. If you're wondering about the file extension, "htaccess" is the extension—there's just nothing before the period. Don't try to rename the file to anything else (e.g. file.htaccess or htaccess.txt).
- .htaccess files can be edited with any plain text editor (e.g. Windows Wordpad)
- htaccess files must be uploaded in ASCII mode (not binary). You may need to CHMOD the file to 644 or (RW-R--R--).
- You can add commented lines using the hash (pound) sign: # (see the example below)
- There is a small performance hit using .htaccess, as opposed to using the main server configuration file. If you have root access you might like to use the main server configuration file instead (this is recommended by apache.org).
Example
This is a simple example of a .htaccess file:
# Enable URL re-writing:
RewriteEngine on
# Redirect users to "www" if necessary:
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
# Permanently redirect a file within the same domain:
RedirectMatch permanent ^/path/to/old-file.html$ http://www.example.com/path/to/new-file.html
# Permanently redirect a file to a new domain:
RewriteRule http://www.old-domain.com/old-file.html http://www.new-domain.com/new-file.html
# Parse html files as if they were .shtml:
AddHandler server-parsed html htm
# Define your preferred default index pages (the last option redirects to the site root index page):
DirectoryIndex index.html index.htm default.htm index.php index.cgi index.pl /index.html
# Prevent certain browsing agents from stealing your stuff:
RewriteCond %{HTTP_USER_AGENT} Curl [OR]
RewriteCond %{HTTP_USER_AGENT} HTTrack [OR]
RewriteCond %{HTTP_USER_AGENT} WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} Wget
RewriteRule ^(.*) - [F]