Basics of .htaccess

What is .htaccess? Its a simple ASCII text file that resides in your site's main directory and/or any other directory. Key uses of .htaccess include customizing error pages, managing redirects, implementing password protection, and a lot more. You need to enable "mod_rewrite" in order for .htaccess to work.

.htaccess Tutorial

What is .htaccess?

htaccess stands for Hypertext Access, which is default name for Apache configuration file. Lets not confuse .htaccess with a filename its rather an extension without any filename. This file works on any directory it resides in, which can be either website's root directory or any sub-directory.

How to create .htaccess file?

You don't need any special program for creating .htaccess file just simple text editor would be enough. When you save .htaccess file just keep in mind this file has no name just ".htaccess" extension so when you save, choose "All Files" in file type box and file name must be only ".htaccess".

Error Redirection with .htaccess

You can redirect users to specific pages when they try to access invalid pages. For example if a user tries to visit a page that does not exist causing 404 error. Show a 404 page for 404 errors with .htaccess like this:

ErrorDocument 404 /404.html 

Common Error Codes:

Code Description
400 Bad Request
401 Unauthorized
403 Forbidden Access
404 Not Found
500 Internal Server Error
502 Bad Gateway
504 Gateway Timeout

Custom Redirection with .htaccess

However if you ever wanted to redirect a specific old page to any new page you can also do it with .htaccess. Redirect user from old page to a new page it with .htaccess like this:

Redirect /OldDir/OldFile.html /NewDir/NewFile.html 

Password Protection with .htaccess 

You can also password protect web pages. To achieve this you will need to create a new file (.htpasswd) that houses all the username and passwords. You have to create ".htpasswd" file same as you created .htaccess. The structure of .htpasswd file to store usernames and passwords is like:

admin:123456
user:123123

After creating .htpasswd, it is important that you add the below content to your .htaccess file. Remember this password protection will apply on the directory ".htaccess" resides in and all the subdirectories.

AuthUserFile /absolute/pathto/.htpasswd
AuthType Basic
AuthName "Authorization Required"
require valid-user

Deny Users via IP Address

You can also restrict visitors from specific IP Address from viewing your web pages. For example if you wanted to block IP "199.155.88.25" the code would be as below:

order allow,deny
deny from 199.155.88.25 
allow from all 
NOTE: .htaccess file requires "mod_rewrite" to be enabled.