A .htaccess file is a configuration file supported by several web servers(including Apache), that allows for decentralized management(local) of web server configuration. .htaccess supports quite a few modifications and it’s quite flexible and customizable. The original purpose of .htaccess was to allow directory access control(requiring a password to access the content). Its functionality nowadays is way beyond access control since the .htaccess file override many other configuration settings such as content type, character set, handlers, and so on. The most common functions for .htaccess are used to facilitate the following:
Here are a few .htaccess examples to achieve certain functionality.
Deny all traffic to the site
Deny from all
Deny all traffic and allow only one IP address
Order deny,allow
Deny from all
Allow from 1.2.3.4
where 1.2.3.4 is the IP address that you to be permitted for access.
This can go even further and redirect all the visitors to a different page while only your IP address(1.2.3.4) can access it:
ErrorDocument 403 http://www.google.com/
Order deny,allow
Deny from all
Allow from 1.2.3.4
Redirect one file to a new one
Redirect 301 /old/file.html /new/file.html
Redirect an entire directory
RedirectMatch 301 /folder(.*) /$1
Redirect all traffic to www
This is quite handy if you want to keep your traffic and links using www:
RewriteCond %{REQUEST_URI} !^/(robots\.txt|favicon\.ico|sitemap\.xml)$
RewriteCond %{HTTP_HOST} !^www\.hostingstuff\.net$ [NC]
RewriteRule ^(.*)$ /$1 [R=301,L]
Setup custom error documents based on HTTP response code
The syntax is quite simple and straight forward:
ErrorDocument RESPONSE_CODE PAGE
Here are a few .htaccess examples for 403, 404, 500 error codes:
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Enable directory listing and fancy indexing, declare the DirectoryIndex variable
Options +Indexes
IndexOptions +FancyIndexing
DirectoryIndex index.html index.php
Disable directory listing
Options -Indexes